Microsoft.Office.Interop.Excel不使用索引添加新行

时间:2017-11-17 19:47:48

标签: c# excel

我正在尝试将列表转换为excel文件。但我不认为使用WorkSheet.Cells[i, y] = "value"会起作用。我想知道是否有一种在Excel的最后一行末尾添加行的一般方法。

public void AttorneysToExcelFile(List<Scraper.StaggingAttorney> liveScraperAttorneys, string FileName)
{
    Excel.Workbook WorkBook = ExcelApp.Workbooks.Add();
    Excel.Worksheet xlWorkSheet = (Excel.Worksheet)WorkBook.Worksheets.get_Item(1);
    xlWorkSheet.Name = "No Category";
    liveScraperAttorneys = liveScraperAttorneys.OrderBy(x=>x.Department).ToList();


    xlWorkSheet.Cells[1, 1] = "caseNumber";
    xlWorkSheet.Cells[1, 2] = "Category";
    xlWorkSheet.Cells[1, 3] = "Names";
    xlWorkSheet.Cells[1, 4] = "Email";
    xlWorkSheet.Cells[1, 5] = "Address";

    for (int i=2; i<liveScraperAttorneys.Count; i++)
    {
        Scraper.StaggingAttorney attorney = liveScraperAttorneys[i];

        xlWorkSheet.Cells[i, 1] = attorney.caseNumber;
        xlWorkSheet.Cells[i, 2] = attorney.Category;
        xlWorkSheet.Cells[i, 3] = attorney.Names;
        xlWorkSheet.Cells[i, 4] = attorney.Email;
        xlWorkSheet.Cells[i, 5] = attorney.Address;
    }
    WorkBook.SaveAs(FileName);
    WorkBook.Close();
}

你可以看到我依靠我。如果我能立刻做到这一点也会有所帮助。另外,我想知道我添加标题的方式是否正确。

1 个答案:

答案 0 :(得分:1)

迭代Interop对象非常慢。将您的列表转换为object[,],然后将其分配给Excel range.Value。添加标题行作为数组中的第一个元素,然后将数据添加为其余元素。 range是与您的数组具有相同维度的一系列单元格。也就是说,列表中的项目数量与对象中的属性数量相同。