2014-09-02 24 views
0

我试图找出将multi dimensional C# list插入excel sheet并使用interop assembly的方法我的列表中有多行数据分布在8列上。但是,当我执行我的查询扔我一个COM Exception from HRESULT: 0x800A03EC,我有以下代码将多维列表插入到Excel表中时发生COM异常

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); 
    } 
} 

StructureDS结构

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]; 被抛出的错误,我无法找到一个解决这个问题。我可以知道我错在哪里吗?

+0

你还没有说过哪一行会抛出错误。 – user845279 2014-09-02 18:36:22

+0

它在worksheet1.Cells [i,j] = listExport [i - 1],我编辑了问题 – DoIt 2014-09-02 18:57:33

+0

我认为你需要'worksheet1.Cells [i,j] .Value = listExport [i - 1];'另外,我不知道StructureDS是什么,但是您可能需要一个属性,而不是结构本身。 – 2014-09-02 18:59:58

回答

2

您正试图将单元格设置为结构。您需要将其设置为结构的其中一个字段。喜欢的东西:

worksheet1.Cells[i, j].Value = listExport[i - 1].over; 

那(.over)可能是错误的领域beause我不知道哪一个你真正想要把在细胞中。