将数据插入到单个Excel工作簿上的多个工作表中

时间:2014-09-03 19:12:26

标签: c# excel list interop

我正在研究一种方法,该方法使用以下代码将来自两个不同C#列表的数据导出到单个工作簿中的两个excel工作表中

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++)
                {

                        worksheet1.Cells[i+1,1] = listExport[i - 1].time.ToString("HH:mm:ss");
                        worksheet1.Cells[i+1, 2] = listExport[i - 1].CC;
                        worksheet1.Cells[i+1, 3] = listExport[i - 1].term;                        

                }

                Microsoft.Office.Interop.Excel._Worksheet worksheet2 = null;
                worksheet2 = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet2"];
                worksheet2 = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;

                for (int i = 1; i < AxiomSubSet.Count + 1; i++)
                {

                    worksheet2.Cells[i + 1, 1] = AxiomSubset[i - 1].time.ToString("HH:mm:ss");
                    worksheet2.Cells[i + 1, 2] = AxiomSubset[i - 1].CC;

                }

                string fileDestination = @"S:\Axiom Derivatives\Parser Project\axiom.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();

但是当我运行上面的方法时,第一个列表已成功处理,但是当在下一行分配第二个工作表时,它向我发出了错误Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX))

worksheet2 ==Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets["Sheet2"];

这不是处理多个Excel工作表的方法吗?

1 个答案:

答案 0 :(得分:2)

第二个工作表可能不称为Sheet2。 最好只使用索引。

此外,您需要调用Activate以使Sheet 2成为活动工作表:

在第一张表

之前
worksheet1 = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets[1];
workbook.Sheets[1].Activate(); 
在第二张之前

worksheet2 = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets[2];
workbook.Sheets[2].Activate();