public bool ExportToCsv(DataSet src, string fileName)
{
StreamWriter writer = null;
fileName = Server.MapPath("Test") + "//" + fileName;
try
{
if (src == null || src.Tables.Count == 0) throw new Exception("dataset is null or has not table in dataset");
for (int i = 0; i < src.Tables.Count; i++)
{
if (i > 0)
fileName = fileName.Substring(0, fileName.IndexOf('.')) + i + fileName.Substring(fileName.IndexOf("."));
writer = new StreamWriter(fileName);
DataTable dt = src.Tables[i];
StringBuilder sb = new StringBuilder();
for (int j = 0; j < dt.Columns.Count; j++)
{
string colName = dt.Columns[j].ColumnName;
if (colName.IndexOf(',') > -1)
colName = colName.Insert(0, "/"").Insert(colName.Length + 1, "/"");
sb.Append(colName);
if (!colName.Equals(""))
if (j != dt.Columns.Count - 1)
sb.Append(",");
}
writer.WriteLine(sb.ToString());
sb = new StringBuilder();
string temp = "";
for (int j = 0; j < dt.Rows.Count; j++)
{
DataRow dr = dt.Rows[j];
for (int k = 0; k < dt.Columns.Count; k++)
{
object o = dr[k];
if (o != null)
temp = o.ToString();
if (temp.IndexOf(',') > -1)
temp = temp.Insert(0, "/"").Insert(temp.Length + 1, "/"");
sb.Append(temp);
if (k != dt.Columns.Count - 1)
sb.Append(",");
}
writer.WriteLine(sb.ToString());
sb = new StringBuilder();
}
writer.Close();
}
}
catch (Exception ex)
{
throw new Exception("Save csv error", ex);
}
finally
{
if (writer != null) writer.Close();
}
return true;
}
asp.net(c#) 导出csv文件
最新推荐文章于 2024-07-08 16:21:06 发布