将两个列表的内容写入同一个excel工作簿中的两个不同工作表

时间:2014-08-29 16:47:22

标签: c# excel list

我正在研究几个C# list需要写入excel工作簿到两个不同的工作表Sheet1 and Sheet2但不知道如何使用interop处理excel我使用以下方法

public void ExportListToExcel(List<String> 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 worksheet = null;
                worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.Sheets[sheetName];
                worksheet = (Microsoft.Office.Interop.Excel._Worksheet)workbook.ActiveSheet;

                for (int i = 1; i < listExport.Count + 1; i++)
                {
                    //int count = 1;
                    worksheet.Cells[i, 1] = listExport[i - 1];
                    //count++;
                }
                string fileDestination = @"C:\Atlas Applications\AxiomParser\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();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }

ExportListToExcel(listMultiRowThreeWay,&#34;工作表Sheet&#34);  ExportListToExcel(listMultiRowButterFly,&#34; Sheet2&#34;);

我在方法中用两个工作表名称调用上面的方法两次但是在第二次执行方法时它给了我一个invalid index error  enter image description here

**Is there a better way to do it?**

0 个答案:

没有答案