// 点击CSV生成按钮的时候
protected void btnCSV_Click(object sender, EventArgs e)
{
try
{
// csvLabel是获取到的要存到csv的数据
DataSet csvLabel = DataSet csvLabel = SubSQLFunction1.getMS001Data(this.LangKbn, this.Name, this.DbConnection);
DataSet tmpds = this.getCSVData(this.DbConnection);
DataTable dtOutput = new DataTable();
for (int i = 28; i <= 41; i++)
{
dtOutput.Columns.Add(csvLabel.Tables[0].Rows[0][i].ToString(), typeof(String));
}
//foreach (MasterDataSet.Z4011090_01Row row in dsMeisai.Z4011090_01)
for (int i = 0; i < tmpds.Tables[0].Rows.Count; i++)
{
dtOutput.Rows.Add(new object[] {
tmpds.Tables[0].Rows[i][0],
tmpds.Tables[0].Rows[i][1],
tmpds.Tables[0].Rows[i][2],
tmpds.Tables[0].Rows[i][3],
tmpds.Tables[0].Rows[i][4],
tmpds.Tables[0].Rows[i][5],
tmpds.Tables[0].Rows[i][6],
tmpds.Tables[0].Rows[i][7],
tmpds.Tables[0].Rows[i][8],
tmpds.Tables[0].Rows[i][9],
tmpds.Tables[0].Rows[i][10],
tmpds.Tables[0].Rows[i][11],
tmpds.Tables[0].Rows[i][12],
tmpds.Tables[0].Rows[i][13]
});
}
// CSV
SubFunction1.csvWriter(this.Name + "_" + this.Title, dtOutput, this);
}
catch (System.Threading.ThreadAbortException)
{
this.infoLogWrite(this.getLogMessage(SubFunction1.getEndLogMessage(this.LangKbn)), this.Name);
return;
}
catch (Exception ex)
{
this.errorLogWrite(ex.ToString(), this.Name);
throw ex;
}
}
public static void csvWriter(string fileName, DataTable dt, WebBase.UI.WebFormBase webForm)
{
// CSV全部信息
StringBuilder sbCSVAllLine = new StringBuilder();
// CSV単行信息
StringBuilder sbCSVLine = new StringBuilder();
// column信息保存
bool isFirstTime = true;
for (int col = 0; col < dt.Columns.Count; col++)
{
// 第一次不需要加逗号
if (isFirstTime)
isFirstTime = false;
else
sbCSVLine.Append(",");
// column名
sbCSVLine.Append(dt.Columns[col].ColumnName.Trim());
}
// 全部信息保存
sbCSVAllLine.AppendLine(sbCSVLine.ToString());
// 各行设定
for (int row = 0; row < dt.Rows.Count; row++)
{
DataRow drRow = dt.Rows[row];
isFirstTime = true;
sbCSVLine.Clear();
for (int col = 0; col < dt.Columns.Count; col++)
{
// 非第一次
if (isFirstTime)
isFirstTime = false;
else
sbCSVLine.Append(",");
Type datatype = dt.Columns[col].DataType;
// 文字列
if (datatype.ToString().Equals("System.String"))
{
sbCSVLine.Append(string.Format("\"{0}\"", drRow[col].ToString()));
}
// 数值列
else
{
sbCSVLine.Append(drRow[col].ToString());
}
}
// 全部信息保存
sbCSVAllLine.AppendLine(sbCSVLine.ToString());
}
// 写文件
webForm.Response.ContentType = "application/octet-stream";
string strFileNameEncode = HttpUtility.UrlEncode(fileName + ".csv");
webForm.Response.AddHeader("Content-Disposition", "attachment; filename=" + strFileNameEncode);
Encoding encoding = Encoding.GetEncoding("UTF-8");
webForm.Response.BinaryWrite(encoding.GetBytes(sbCSVAllLine.ToString()));
webForm.Response.Flush();
webForm.Response.End();
}
【C#】CSV文件生成
最新推荐文章于 2024-01-03 13:33:36 发布