如何创建Excel工作表并将List中的数据插入其中?

时间:2013-03-22 06:55:23

标签: c# .net excel asp.net-mvc-4 export-to-excel

我有一个带有一组URL的excel表,我正在从excel中逐个读取这些URL,并将URL传递给另一个服务以检索一些数据。As in this link 现在,我有一个像这样的课程

 internal class Record
    {
        public string Id { get; set; }
        public string url { get; set; }
        public string Name { get; set; }
        public string Age { get; set; }
    }

现在,我创建了一个类List<Record> rec= new List<Record>();的列表 从服务我得到大约100条记录,它在列表 rec 。 我想要实现的是创建另一个列名为 Id,Url,Name,Age 的Excel工作表 并将 rec 中的数据逐行传输到Excel工作表。(这与上面链接中的操作相反)excel应该是这样的,

Id              Url                                                                                  Name    Age
1       http://www.sample.com/term=100898731%5Buid%5D&cmd=DetailsSearch&report=xml&format=text        Tom     10
2       http://www.sample.com/term==101120693%5Buid%5D&cmd=DetailsSearch&report=xml&format=text       Jerry   11
3       http://www.sample.com/term==100893225%5Buid%5D&cmd=DetailsSearch&report=xml&format=text       Jose    10 

如何实现相同的??

1 个答案:

答案 0 :(得分:1)

您是否考虑过使用Open XML SDK

using (SpreadsheetDocument spreadSheet = SpreadsheetDocument.Create(
    System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, SPREADSHEET_NAME),
    SpreadsheetDocumentType.Workbook))
{
    // create the workbook
    spreadSheet.AddWorkbookPart();
    spreadSheet.WorkbookPart.Workbook = new Workbook ();     // create the worksheet
    spreadSheet.WorkbookPart.AddNewPart<WorksheetPart>();
    spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet = new Worksheet();

    // create sheet data
    spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.AppendChild(new SheetData());

    // create row
    spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.First().AppendChild(new Row());

    // create cell with data
    spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.First().First().AppendChild(          
          new Cell() { CellValue = new CellValue("101") });

    // save worksheet
    spreadSheet.WorkbookPart.WorksheetParts.First().Worksheet.Save();

    // create the worksheet to workbook relation
    spreadSheet.WorkbookPart.Workbook.AppendChild(new Sheets());
    spreadSheet.WorkbookPart.Workbook.GetFirstChild<Sheets>().AppendChild(new Sheet()
        {
            Id = spreadSheet.WorkbookPart.GetIdOfPart(spreadSheet.WorkbookPart.WorksheetParts.First()),
            SheetId = 1,
            Name = "test"
        });

    spreadSheet.WorkbookPart.Workbook.Save();
}

遍历您的列表并附加更多单元格。