如何从数据源中添加数据以dynamic添加到Excel文件中

我一直在试图找出如何添加单元格,当我使用c#创build我的Excel spreedsheet。 我看到每个人都是通过添加一系列单元来完成的。 我的问题是我不知道细胞的数量。 我希望能够设置列标题和数据填充下他们。 我问很多? 我没有任何源代码,我只是在开始这个旅程之前做的研究。 例子将不胜感激!

我不确定你使用的是什么库,但是我在当前的开发中使用EPPLus ,它的function就像一个魅力。 当您查看他们的CodePlex页面时,只需向下滚动查看一些示例和截图,即可了解您正在处理的内容。 来源也有很多例子。 这是我的应用程序中的一个片段:

// Setup a new Excel package (workbook). using (var package = new ExcelPackage(newFile)) { // Create aa 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(); } 

正如你所看到的那样,这很简单,你可以把它变成dynamic的。