在Excel单元格中显示列表

时间:2014-07-31 00:22:35

标签: c# excel

我想用c#在excel单元格中显示一个列表。问题是只有列表的最后一项显示在excel表格中。任何帮助? 这是我的代码:

 Excel.Application xlApp ;
        Excel.Workbook xlWorkBook ;
        Excel.Worksheet xlWorkSheet ;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);

        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Cells[1, 1] = "Nb de fonction";
        xlWorkSheet.Cells[1, 3] = "list de fonction supprimé";
        xlWorkSheet.Cells[1, 8] = "list de fonction ajouté";
        foreach (var item in listfunc1)
        {
            xlWorkSheet.Cells[3, 8] = item;
            xlWorkSheet.Cells[7, 8] = item;
        }
        xlWorkSheet.Cells[1, 12] = "list de commentaire supprimé";
        xlWorkSheet.Cells[1, 16] = "list de commentaire ajouté";
        xlWorkSheet.Cells[1, 19] = "list d'entête supprimé";
        xlWorkSheet.Cells[1, 16] = "list d'entête ajouté";

        xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        MessageBox.Show("Excel file created , you can find the file c:\\Documents\\csharp-Excel.xls");

2 个答案:

答案 0 :(得分:0)

尝试更改此内容:

foreach (var item in listfunc1)
    {
        xlWorkSheet.Cells[3, 8] = item;
        xlWorkSheet.Cells[7, 8] = item;
    }

对此:

   int i=0;
   foreach (var item in listfunc1)
    {
        xlWorkSheet.Cells[3+i, 8] = item;
        xlWorkSheet.Cells[7+i, 8] = item;
        i++;
    }

答案 1 :(得分:0)

我做了一些更改,现在可以使用了

 int row = 3;
        int col = 8;
        foreach (var item in listfunc1)
        {
            xlWorkSheet.Cells[row, col] = item;
            row++;
            if (listfunc1.IndexOf(item) == listfunc1.Count - 1)
                col = 1;

        }