2014-04-16 77 views
0

我一直在試圖找出如何在使用c#創建Excel spreedsheet時添加單元格。我看到每個人都通過添加一系列單元格來完成它。我的問題是我不知道細胞的數量。我希望能夠設置列標題和數據填充在它們下面。我要求很多嗎?我沒有任何源代碼,我只是在開始這個旅程之前進行研究。例子將不勝感激!如何將數據源中的數據添加到動態添加到Excel文件中

+0

我意識到你問的是Excel,但讓我拋出這個選項:創建一個CSV文件(可以在Excel中打開)怎麼樣?有時使用CSV並不是最優雅的選項,但它更容易一些,可能適合您的需求。 – Baub

回答

2

我不確定你正在使用什麼庫,但我在當前的開發中使用了EPPLus,它的功能就像一個魅力。當您查看他們的CodePlex頁面時,只需向下滾動查看一些示例和截圖,即可瞭解您正在處理的內容。源代碼中也有很多例子。下面是從我的應用程序的代碼段:

// Setup a new Excel package (workbook). 
using (var package = new ExcelPackage(newFile)) 
{ 
    // Create a a new worksheet in the workbook. 
    var worksheet = package.Workbook.Worksheets.Add("Files"); 

    // Set the titles for the columns. 
    worksheet.Cells[1, 1].Value = "Date"; 
    worksheet.Cells[1, 2].Value = "Time"; 
    worksheet.Cells[1, 3].Value = "File Name"; 
    worksheet.Cells[1, 4].Value = "Location"; 
    worksheet.Cells[1, 5].Value = "Size"; 
    worksheet.Cells[1, 6].Value = "Comments"; 

    // Set formatting for the titles. 
    using (var range = worksheet.Cells[1, 1, 1, 6]) 
    { 
     range.Style.Font.Bold = true; 
     range.Style.Fill.PatternType = ExcelFillStyle.Solid; 
     range.Style.Fill.BackgroundColor.SetColor(Color.RoyalBlue); 
     range.Style.Font.Color.SetColor(Color.White); 
     range.Style.WrapText = true; 
    } 

    // Set the titles to repeat. 
    worksheet.PrinterSettings.RepeatRows = new ExcelAddress("1:1"); 

    // Set worksheet to print in landscape. 
    worksheet.PrinterSettings.Orientation = eOrientation.Landscape; 

    // Set the worksheet to fit all columns. 
    worksheet.PrinterSettings.FitToPage = true; 
    worksheet.PrinterSettings.FitToWidth = 1; 
    worksheet.PrinterSettings.FitToHeight = 0; 

    // Set the border to separate data. 
    worksheet.Cells.Style.Border.Left.Style = ExcelBorderStyle.Thin; 
    worksheet.Cells.Style.Border.Top.Style = ExcelBorderStyle.Thin; 
    worksheet.Cells.Style.Border.Right.Style = ExcelBorderStyle.Thin; 
    worksheet.Cells.Style.Border.Bottom.Style = ExcelBorderStyle.Thin; 

    for (int i = 0, row = 2; i < files.Count; i++, row++) 
    { 
      worksheet.Cells[String.Format("A{0}", row)].Value = files[i].Date; 
      worksheet.Cells[String.Format("B{0}", row)].Value = files[i].Time; 
      worksheet.Cells[String.Format("C{0}", row)].Value = files[i].FileName; 
      worksheet.Cells[String.Format("D{0}", row)].Value = files[i].Location; 
      worksheet.Cells[String.Format("E{0}", row)].Value = files[i].Size; 
      worksheet.Cells[String.Format("E{0}", row)].Style.Numberformat.Format = "0"; 
      worksheet.Cells[String.Format("F{0}", row)].Value = files[i].Comments; 
    } 

    // Auto fit all columns. 
    worksheet.Cells.AutoFitColumns(); 

    package.Save(); 
} 

正如你看到的,這是相當簡單的,你可以讓你想要它是動態的。