将多维列表插入excel工作表时出现COM异常
本文关键字:COM 异常 工作 列表 插入 excel | 更新日期: 2023-09-27 18:20:19
我试图找到一种方法,使用interop assembly
将multi dimensional C# list
插入excel sheet
。我的列表中有几行数据,分布在8列中。但当我执行查询时,它给了我一个COM Exception from HRESULT: 0x800A03EC
,我有下面的代码
public void ExportStructureListToExcel(List<StructuresDS> listExport, string sheetName)
{
try
{
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet1 = null;
worksheet1 = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet1"];
worksheet1 = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;
for (int i = 1; i < listExport.Count + 1; i++)
{
for (int j = 1; j < 8; j++)
{
worksheet1.Cells[i, j] = listExport[i - 1];
}
}
string fileDestination = @"S:'Parser Project'sde.xls";
if (File.Exists(fileDestination))
{
File.Delete(fileDestination);
}
workbook.SaveAs(fileDestination, Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
workbook.Close(true, Type.Missing, Type.Missing);
Process.Start(fileDestination);
app.Quit();
}
catch (Exception e)
{
MessageBox.Show(e.Message);
}
}
结构DS结构
public class StructuresDS
{
public DateTime time;
public string CC;
public string term;
public string strike;
public string strategy;
public double? premium;
public int volume;
public double ratio;
public string over;
}
**Inserting elements to the List**
listStructures.Add(new StructuresDS
{
time = Convert.ToDateTime(AxiomSubSet[0].time.ToString("HH:mm:ss")),
CC = AxiomSubSet[0].CC,
term = listCodedTerms[0],
strike = (Convert.ToDouble(AxiomSubSet[0].strike) * 100).ToString(),
strategy = AxiomSubSet[0].strategy,
premium = Convert.ToDouble(AxiomSubSet[0].price),
volume = Convert.ToInt32(AxiomSubSet[0].quantity)
});
在worksheet1.Cells[i, j] = listExport[i - 1];
处引发错误我找不到解决这个问题的办法。我能知道我错在哪里吗?
您正试图将一个单元格设置为该结构。您需要将其设置为结构的某个字段。类似于:
worksheet1.Cells[i, j].Value = listExport[i - 1].over;
这(.over)可能是错误的字段,因为我不知道你到底想把哪个字段放在单元格中。