【发布时间】:2013-12-05 18:07:07
【问题描述】:
Destinations || DeparturePort || Count || % of Search ||
--------------------------------------------------------------
Caribbean Eastern || FLL,MIA || 2 || 0.03 ||
South America || LIM || 1 || 0.02 ||
导出到excel的代码如下:
using (System.IO.StreamWriter tempFile = new System.IO.StreamWriter(Response.OutputStream))
{
string cols = "";
foreach (DataColumn dc in dt1.Columns)
{
cols += dc.ColumnName.ToString() + ",";
}
#region Writetofile
System.Collections.Generic.List<string> fileRows = new System.Collections.Generic.List<string>();
for (int i = 0; i < dt1.Rows.Count; i++)
{
string strToWrite = string.Empty;
for (int j = 0; j < dt1.Columns.Count; j++)
{
if (dt1.Rows[i][j].ToString().IndexOf(',') != 0)
{
strToWrite += "\"" + dt1.Rows[i][j].ToString() + "," + "\"";
}
else
strToWrite += dt1.Rows[i][j].ToString() + ",";
}
fileRows.Add(strToWrite);
}
#endregion
this.CreateExportFile(cols, fileRows, fileName, string.Empty);
Response.End();
}
在excel中导出的实际代码如下:
internal void CreateExportFile(string colHeader, List<string> arrL, string fileName, string fileType)
{
#region New code
if(arrL != null && arrL.Count > 0)
{
Response.ContentType = (fileType == null || fileType == string.Empty) ? "text/csv" : fileType;
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
using(System.IO.StreamWriter sw = new System.IO.StreamWriter(Response.OutputStream))
{
sw.WriteLine(colHeader);
for(int i = 0; i < arrL.Count; i++)
sw.WriteLine(arrL[i]);
sw.Flush();
} // using
Response.End();
} // if we have data
#endregion
}
当 Column 具有单个值时,这可以正常工作。但由于列具有多个值,如 MIA、FLL,它将它们分隔在不同的列中。我可以在此处进行哪些更改?
提前谢谢你。
【问题讨论】:
-
您需要将值括在引号中,并在必要时转义引号。 CSV 文件没有标准,但包括 Excel 在内的大多数阅读器都支持引号分隔。
-
再次查看您的代码。
Response.ContentType = text/csv。 csv = 逗号分隔值。因此,当然任何逗号都将充当分隔符。您必须查看带引号的分隔符。 -
Response.ContentType = (fileType == null || fileType == string.Empty) ? "text/csv" : fileType;您的内容类型是 csv ,它会将您的列值(MIA,FLL) 视为不同的列。