我正在将数据导出到Excel工作表。我有一个名为totalWorkingHours的字段作为字符串,它将小时和分钟保存为" hh:mm"例如" 119:20&#34 ;.但是excel会将其读作时间戳并为其添加秒数:" 119:20:00"。我想删除秒,值应显示为" 119:20"只要。
以下代码返回内存流,然后导出到excel:
public static MemoryStream GetCSV(string[] fieldsToExpose, DataTable data)
{
MemoryStream stream = new MemoryStream();
using (var writer = new StreamWriter(stream))
{
for (int i = 0; i < fieldsToExpose.Length; i++)
{
if (i != 0) { writer.Write(","); }
writer.Write("\"");
writer.Write(fieldsToExpose[i].Replace("\"", "\"\""));
writer.Write("\"");
}
writer.Write("\n");
foreach (DataRow row in data.Rows)
{
for (int i = 0; i < fieldsToExpose.Length; i++)
{
if (i != 0) { writer.Write(","); }
writer.Write("\"");
if (row[fieldsToExpose[i]].GetType() == typeof(DateTime))
{
var Val = (DateTime)row[fieldsToExpose[i]];
string output = Val.ToString("dd-MMM-yyyy hh:mm");
if (Val.TimeOfDay == new TimeSpan(0, 0, 0))
{
output = Val.ToString("dd-MMM-yyyy");
}
writer.Write(output.Replace("\"", "\"\""));
}
else
{
writer.Write(row[fieldsToExpose[i]].ToString().Replace("\"", "\"\""));
}
writer.Write("\"");
}
writer.Write("\n");
}
}
return stream;
}
答案 0 :(得分:2)
我认为这样做的好方法是在你的字符串之前添加一个空格,例如'110:20',这样就行了,excel会以字符串格式读取它并且不会转换它迄今为止的格式。希望你能得到解决方案