Skip to content

Instantly share code, notes, and snippets.

@121jigowatts
Created May 28, 2015 08:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 121jigowatts/660fbe7fd62c77db1a42 to your computer and use it in GitHub Desktop.
Save 121jigowatts/660fbe7fd62c77db1a42 to your computer and use it in GitHub Desktop.
[ASP.NET]GridViewからExcel出力する
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ClassLibrary1;
using WebApplication1.Services;
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
private PersonService _service = new PersonService();
private List<Person> dataList = new List<Person>() {
new Person() { ID = 1, Name = "TEST01", Address = "Tokyo" },
new Person() { ID = 2, Name = "TEST02", Address = "Yokohama" },
new Person() { ID = 3, Name = "TEST03", Address = "Osaka" },
new Person() { ID = 4, Name = "TEST04", Address = "Kyoto" },
new Person() { ID = 5, Name = "TEST05", Address = "Kobe" }
};
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = _service.CreateDataSet<Person>(dataList);
PersonGridView.DataSource = ds;
PersonGridView.DataBind();
}
}
//htmlのtableタグで出力したデータをxlsファイルとして無理やり認識させている
//このためxlsx形式だとうまくいかない
//また、日本語が文字化けするのでエンコーディングしてあげること
protected void btnExcelExport_Click(object sender, EventArgs e)
{
var path = Server.MapPath("./Report/" + "Sample.xls");
FileInfo fi = new FileInfo(path);
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
DataGrid dataGrid = new DataGrid();
DataSet ds = _service.CreateDataSet<Person>(dataList);
dataGrid.DataSource = ds;
dataGrid.DataBind();
dataGrid.RenderControl(htmlWriter);
string directory = path.Substring(0, path.LastIndexOf("\\"));
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
StreamWriter sw = new StreamWriter(path, true);
stringWriter.ToString().Normalize();
sw.Write(stringWriter.ToString());
sw.Flush();
sw.Close();
WriteAttachment(fi.Name, "application/vnd.ms-excel", stringWriter.ToString());
//WriteAttachment(fi.Name, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", stringWriter.ToString());
}
public static void WriteAttachment(string fileName, string fileType, string content)
{
HttpResponse response = HttpContext.Current.Response;
response.ClearHeaders();
response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
response.ContentType = fileType;
//Encodingここから
response.ContentEncoding = System.Text.Encoding.Unicode;
response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
//ここまで
response.Write(content);
response.End();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment