C#-使用HttpContext将dataTable导出到Excel-格式化单元格值

时间:2018-12-14 12:54:10

标签: c# asp.net excel webforms httpcontext

我从数据表中导出了一个excel文件。 我使用了HttpContext。 我需要具备:

enter image description here

但是我的结果是:

enter image description here

这是我的代码:

    protected void Export_Click(object sender, EventArgs e) {
        DataTable dt = GParam.GetreferentielContacts();
        HttpContext context = HttpContext.Current;
        context.Response.Clear();
        foreach (DataColumn column in dt.Columns){
            context.Response.Write(column.ColumnName + "\t");
        }
        context.Response.Write(Environment.NewLine);
        foreach (DataRow row in dt.Rows){
            for (int i = 0; i < dt.Columns.Count; i++){
                context.Response.Write(row[i].ToString() + "\t");
            }
            context.Response.Write(Environment.NewLine);
        }
        context.Response.ContentType = "application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        context.Response.AppendHeader("Content-Disposition", "attachment; filename=test_export.xlsx");
        context.Response.End();
    }

格式化第一列的参数是什么? 谢谢

1 个答案:

答案 0 :(得分:0)

已解决 我用的是EpPlus库 代码在下面

    protected void Export_Click(object sender, EventArgs e) {
        DataTable dt = GParam.GetreferentielContacts();
        HttpContext context = HttpContext.Current;
        context.Response.Clear();
        context.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        context.Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode("Logs.xlsx", System.Text.Encoding.UTF8));
        using (ExcelPackage pck = new ExcelPackage()) {
            ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Logs");
            ws.Cells["A1"].LoadFromDataTable(dt, true);
            var ms = new System.IO.MemoryStream();
            pck.SaveAs(ms);
            ms.WriteTo(Response.OutputStream);
        }
        context.Response.End();
    }