我的代码生成7张纸,然后将它们放入Excel工作簿中。我想做的是将除第一张纸以外的所有图纸的第一列设置为“日期”。以下是我一直在尝试的方法,但似乎不起作用。显示的日期是一个随机数,例如43,349。
for (var i = 0; i < ds.Tables.Count; i++)
{
var sheetName = i < sheetNames.Count
? sheetNames[i]
: String.Format("Sheet{0}", sheetNames.Count - i);
var ws = package.Workbook.Worksheets.Add(sheetName);
ws.Cells["A1"]
.LoadFromDataTable(i == 0 ? Transpose(ds.Tables[i].Copy()).DefaultView.ToTable() : ds.Tables[i],
true, TableStyles.Medium1);
ws.Column(1).Style.Numberformat.Format = "yyyy-mm-dd";
ws.Column(1).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
ws.Cells[ws.Dimension.Address].AutoFitColumns();
ws.Cells["A:H"].Style.Numberformat.Format = "#,##0";
}
答案 0 :(得分:1)
只需添加“ if”语句。如果i> 0,则设置日期:
for (var i = 0; i < ds.Tables.Count; i++)
{
var sheetName = i < sheetNames.Count
? sheetNames[i]
: String.Format("Sheet{0}", sheetNames.Count - i);
var ws = package.Workbook.Worksheets.Add(sheetName);
ws.Cells["A1"].LoadFromDataTable(i == 0
? Transpose(ds.Tables[i].Copy()).DefaultView.ToTable()
: ds.Tables[i],true, TableStyles.Medium1);
if (i > 0)
{
ws.Cells["A:H"] = "yyyy-mm-dd";
ws.Column(1).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
}
ws.Cells[ws.Dimension.Address].AutoFitColumns();
}
答案 1 :(得分:1)
我删除了Numberformat的最后一行,并将其放在if()之前,并且可以正常工作。原来,它正在应用日期,但最后一行用于将日期转换回数字格式。
for (var i = 0; i < ds.Tables.Count; i++)
{
var sheetName = i < sheetNames.Count
? sheetNames[i]
: String.Format("Sheet{0}", sheetNames.Count - i);
var ws = package.Workbook.Worksheets.Add(sheetName);
ws.Cells["A1"].LoadFromDataTable(i == 0
? Transpose(ds.Tables[i].Copy()).DefaultView.ToTable()
: ds.Tables[i],true, TableStyles.Medium1);
ws.Cells["A:H"].Style.Numberformat.Format = "#,##0";
if (i > 0)
{
ws.Cells[1,10] = "yyyy-mm-dd";
ws.Column(1).Style.HorizontalAlignment = OfficeOpenXml.Style.ExcelHorizontalAlignment.Left;
}
ws.Cells[ws.Dimension.Address].AutoFitColumns();
}