我在c#代码中有下一个函数:
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Reflection;
using System.Windows.Controls;
using Excel = Microsoft.Office.Interop.Excel;
public void ToExcel<T>(T[,] array2D, string fullPath)
{
// file path
string strFullFilePathNoExt = fullPath + ".xlsx";
// initializing Excel file & working sheet
Excel.Application ExcelApp = new Excel.Application();
Excel._Workbook ExcelBook;
Excel._Worksheet ExcelSheet;
ExcelBook = ExcelApp.Workbooks.Add(1);
ExcelSheet = (Excel._Worksheet)ExcelBook.ActiveSheet;
for (int i = 0; i < array2D.GetLength(0); i++)
{
for (int j = 0; j < array2D.GetLength(1); j++)
{
ExcelSheet.Cells[i + 1, j + 1] = array2D[i, j].ToString().Trim();
}
}
// Saving file
ExcelApp.Visible = false;
ExcelBook.SaveAs(strFullFilePathNoExt, Excel.XlFileFormat.xlOpenXMLWorkbook, Missing.Value, Missing.Value, false, false, Excel.XlSaveAsAccessMode.xlNoChange,
Excel.XlSaveConflictResolution.xlUserResolution, true,
Missing.Value, Missing.Value, Missing.Value);
ExcelBook.Close(strFullFilePathNoExt, Missing.Value, Missing.Value);
ExcelSheet = null;
ExcelBook = null;
ExcelApp = null;
}
另外,我有下一个使用它的方法:我得到一些字符串2D数组,并希望将它们扩展为一个表和行(对于标题):
SomeFunction()
{
var analysis = new AscendingAnalysis();
string[,] table = analysis.GetPrecedenceRelationTable();
string[,] printTable = new string[table.GetLength(0) + 1, table.GetLength(1) + 1];
// Is only needed for table without nulls (just tested)
for (int i = 0; i < printTable.GetLength(0); i++)
{
for (int j = 0; j < printTable.GetLength(1); j++)
{
printTable[i, j] = "o";
}
}
// first alternative
//for (int i = 1; i < printTable.GetLength(0); i++)
//{
// printTable[i, 0] = (i * i).ToString();
// printTable[0, i] = (i * i).ToString();
//}
//second alternative
//for (int i = 1; i < printTable.GetLength(0); i++)
//{
// printTable[i, 0] = analysis.UniqueItems[i - 1];
// printTable[0, i] = analysis.UniqueItems[i - 1];
//}
for (int i = 1; i < printTable.GetLength(0); i++)
{
for (int j = 1; j < printTable.GetLength(1); j++)
{
printTable[i, j] = table[i - 1, j - 1];
}
}
var doc = new Export();
doc.ToExcel(printTable, "D:\\Table");
}
所以问题出在注释的代码块中:
System.Runtime.InteropServices.COMException:&#34;来自HRESULT的异常: 0x800A03EC&#34;
内部函数,在循环中,当i = 0, j = 52
时(我有数组55x55,但没有问题)。所以,功能部分有效。
请解释一下,为什么它不起作用以及如何解决它。
当然,我没有被迫在excel中导出数据,例如,我可以在DataGrid中进行导出。我只需要在表格中显示结果。但就我而言,excel更方便用于大表和导入(需要在我的项目中进一步使用此表)。