0
我一直在试图找出如何在使用c#创建Excel spreedsheet时添加单元格。我看到每个人都通过添加一系列单元格来完成它。我的问题是我不知道细胞的数量。我希望能够设置列标题和数据填充在它们下面。我要求很多吗?我没有任何源代码,我只是在开始这个旅程之前进行研究。例子将不胜感激!如何将数据源中的数据添加到动态添加到Excel文件中
我一直在试图找出如何在使用c#创建Excel spreedsheet时添加单元格。我看到每个人都通过添加一系列单元格来完成它。我的问题是我不知道细胞的数量。我希望能够设置列标题和数据填充在它们下面。我要求很多吗?我没有任何源代码,我只是在开始这个旅程之前进行研究。例子将不胜感激!如何将数据源中的数据添加到动态添加到Excel文件中
我不确定你正在使用什么库,但我在当前的开发中使用了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();
}
正如你看到的,这是相当简单的,你可以让你想要它是动态的。
我意识到你问的是Excel,但让我抛出这个选项:创建一个CSV文件(可以在Excel中打开)怎么样?有时使用CSV并不是最优雅的选项,但它更容易一些,可能适合您的需求。 – Baub