asp.NetプロジェクトExcelファイルのダウンロード
4499 ワード
単一sheet、転送データset:
複数sheet、転送データセット[]
private void CreateExcel(DataSet ds)
{
string time = DateTime.Now.ToString("yyMMddHHmmss");
string filename = "f" + time;
HttpResponse resp;
resp = Page.Response;
resp.ContentEncoding = Encoding.GetEncoding("utf-8");
resp.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
Response.ContentType = "application/ms-excel";
string colHeaders = "", lsItem = "";
DataTable dt = ds.Tables[0];
DataRow[] myRow = dt.Select("");
int i = 0;
// , \t ,
for (i = 0; i < dt.Columns.Count; i++)
{
if (i == dt.Columns.Count - 1)
{
colHeaders += dt.Columns[i].Caption + "
";
}
else
{
colHeaders += dt.Columns[i].Caption + "\t";
}
}
resp.Write(colHeaders);
foreach (DataRow row in myRow)
{
for (i = 0; i < dt.Columns.Count; i++)
{
if (i == dt.Columns.Count - 1)
{
lsItem += row[i] + "
";
}
else
{
lsItem += row[i] + "\t";
}
}
//
resp.Write(lsItem);
lsItem = "";
}
}
複数sheet、転送データセット[]
private void CreateExcel(DataSet[] ds)
{
Response.ClearContent();
Response.BufferOutput = true;
Response.Charset = "utf-8";
Response.ContentType = "application/ms-excel";
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.ContentEncoding = Encoding.UTF8;
string time = DateTime.Now.ToString("yyMMddHHmmss");
string filename = "data" + time;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename + ".xls");
Response.Write("<?xml version='1.0'?><?mso-application progid='Excel.Sheet'?>");
Response.Write(@"<Workbook xmlns='urn:schemas-microsoft-com:office:spreadsheet'
xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel'
xmlns:ss='urn:schemas-microsoft-com:office:spreadsheet' xmlns:html='http://www.w3.org/TR/REC-html40'>");
for (int i = 0; i < ds.Length; i++)
{
DataTable dt = ds[i].Tables[0];
DataRow[] myRow = dt.Select("");
Response.Write("<Worksheet ss:Name='Sheet" + (i + 1) + "'>");
Response.Write("<Table x:FullColumns='1' x:FullRows='1'>");
Response.Write("\r
<Row ss:AutoFitHeight='1'>");
for (int j = 0; j < dt.Columns.Count; j++)
{
Response.Write("<Cell><Data ss:Type='String'>" + dt.Columns[j].ColumnName +
"</Data></Cell>");
}
Response.Write("\r
</Row>");
foreach (DataRow row in myRow)
{
Response.Write("<Row>");
for (int k = 0; k < dt.Columns.Count; k++)
{
Response.Write("<Cell><Data ss:Type='String'>" + row[k] +
"</Data></Cell>");
}
Response.Write("</Row>");
}
Response.Write("</Table>");
Response.Write("</Worksheet>");
//Response.Flush();
}
Response.Write("</Workbook>");
Response.End();
}