使用OOX将一些数据传递到Excel电子表格时,我遇到了问题。事实是,除了日期以外,其他所有东西都很好用,日期以数字值而不是日期时间格式显示。这是我的代码:
private object ProcessXLSFile(PayeesWorkingHoursFullDataDTO payeesWorkingHoursFullDataDTO)
{
DataTable dt = Functions.ObjectToDataTable(payeesWorkingHoursFullDataDTO.ListWorkingHours);
ExcelPackage pck = new ExcelPackage();
//Create the worksheet
ExcelWorksheet ws = pck.Workbook.Worksheets.Add("WorkSheet1");
//Load the datatable into the sheet, starting from cell A1. Print the column names on row 1
ws.Cells["A1"].LoadFromDataTable(dt, true);
string _range = "G2:G" + (dt.Rows.Count + 1).ToString();
using (ExcelRange col = ws.Cells[_range])
{
col.Style.Numberformat.Format = "#,##0.00";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Right;
}
_range = "J2:J" + (dt.Rows.Count + 1).ToString();
using (ExcelRange col = ws.Cells[_range])
{
col.Style.Numberformat.Format = "dd/MM/yyyy";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
_range = "T2:T" + (dt.Rows.Count + 1).ToString();
using (ExcelRange col = ws.Cells[_range])
{
col.Style.Numberformat.Format = "dd-MM-yyyy";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
//Write it back to the client
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Payee-Grid.xlsx");
Response.BinaryWrite(pck.GetAsByteArray());
Response.End();
throw new NotImplementedException();
}
这些行是应将列转换为日期时间的行:
_range = "J2:J" + (dt.Rows.Count + 1).ToString();
using (ExcelRange col = ws.Cells[_range])
{
col.Style.Numberformat.Format = "dd/MM/yyyy";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
但是那绝对不行。
这是我创建数据表的代码:
public static DataTable ObjectToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
return table;
}
调试列,我已经看到,直到将列格式化为“ dd-MM-yyyy”的行,日期信息仍为datetime格式。我已经尝试了所有方法,但实际上似乎无法使它正常工作。你们对如何使其运作有任何想法吗?
您是否尝试过:
_range = "J2:J" + (dt.Rows.Count + 1).ToString();
using (ExcelRange col = ws.Cells[_range])
{
col.Style.Numberformat.Format = "dd\\/MM\\/yyyy";
col.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
}
有时候,由于未知的原因,您必须逃避某些事情:-)