ファイルのダウンロード

4602 ワード

1.データベースのデータをテキストファイルに保存します.
context.Response.ContentType = "text/plain";

//       

//  Content-Disposition      ,        "    ",      ,filename       

context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlEncode("    .txt"));

DataTable table = SQLHelper.ExecuteReader("select * from userinfo");

foreach (DataRow row in table.Rows)

{

    context.Response.Write(row["name"].ToString() + "\t" + row["age"].ToString() + "\r
"); }

2.データベースのデータをEXCELに保存する
context.Response.ContentType = "application/ms-excel";

context.Response.AddHeader("Content-Disposition", "attachment;filename=" +

    context.Server.UrlEncode("    .xls"));

IWorkbook workbook = new HSSFWorkbook();//new XSSFWorkbook();//xlsx

ISheet sheet = workbook.CreateSheet("    ");

DataTable dt = SQLHelper.ExecuteReader("select * from Users");

for (int i = 0; i < dt.Rows.Count; i++)

{

    IRow excelRow = sheet.CreateRow(i);

    DataRow dataRow = dt.Rows[i];

    ICell cell0 = excelRow.CreateCell(0);

    cell0.SetCellValue((string)dataRow["username"]);



    ICell cell1 = excelRow.CreateCell(1);

    cell1.SetCellValue((int)dataRow["age"]);

}

workbook.Write(context.Response.OutputStream);