DataTable到Excel通过响应对象导出

时间:2012-03-21 13:19:59

标签: c# asp.net excel

我使用asp.net Response对象创建了一个excel文件。但在此文件中,长数字会自动更改为科学记数法。我该如何防止这种情况?

private void WriteToExcelFile(DataTable dt)
{
StringWriter sw = new StringWriter();


sw.Write("Kolon_1\t");
sw.Write("Kolon_2\t");


for (int i = 0; i < dt.Rows.Count; i++)
{
DataRow dr = dt.Rows[i];

sw.Write("\n");
sw.Write(dr["Ad"].ToString() + "\t");
sw.Write(dr["Numara"].ToString() + "\t");


}


Response.Output.Write(sw.ToString());
}

3 个答案:

答案 0 :(得分:4)

我建议您使用EPPlus并将DataTable导出到真正的xlsx文件中,这非常简单,使用此方法可以创建excel文件并将其存储到内存流中:

public static MemoryStream DataTableToExcelXlsx(DataTable table, string sheetName)
{
  MemoryStream Result = new MemoryStream();
  ExcelPackage pack = new ExcelPackage();
  ExcelWorksheet ws = pack.Workbook.Worksheets.Add(sheetName);

  int col = 1;
  int row = 1;
  foreach (DataRow rw in table.Rows)
  {
    foreach (DataColumn cl in table.Columns)
    {
      if (rw[cl.ColumnName] != DBNull.Value)
        ws.Cells[row, col].Value = rw[cl.ColumnName].ToString();
      col++;
    }
    row++;
    col = 1;
  }

  pack.SaveAs(Result);
  return Result;
}

然后将该流提供给客户端:

MemoryStream ms = DataTableToExcelXlsx(myDataTable, "Sheet1");
ms.WriteTo(Response.OutputStream);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=DataTable.xlsx");
Response.StatusCode = 200;

答案 1 :(得分:0)

我们应用风格

r.Cells[columnIndex].Attributes.Add("class", "text"); 
    System.Text.StringBuilder style = new System.Text.StringBuilder();
                style.Append("<style>");
                style.Append("." + "text" + " { mso-number-format:" + "\\@;" + " }");
                style.Append("</style>");
                response.Clear();
                Response.Buffer = true;
                //response.Charset = "";
                //response.Write(sw.ToString());
                Response.Write(style.ToString());

示例功能

  public void GenerateXLS(string pFileName, DataTable pdtSource)
        {
            HttpResponse response = HttpContext.Current.Response;
            response.Clear();
            response.Charset = "";
            // set the response mime type for excel 

            if ((pFileName + "-").ToLower().Contains(".xlsx-"))
            {
                response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            }
            else
            {
                response.ContentType = "application/vnd.ms-excel";
            }

            response.AddHeader("Content-Disposition", "attachment;filename=\"" + pFileName + "\"");

            // create a string writer 
            using (StringWriter sw = new StringWriter())
            {
                using (HtmlTextWriter htw = new HtmlTextWriter(sw))
                {
                    // instantiate a datagrid 
                    GridView gvExport = new GridView();
                    gvExport.DataSource = pdtSource;
                    gvExport.DataBind();
                    //(start): require for date format issue
                    HtmlTextWriter hw = new HtmlTextWriter(sw);

                    foreach (GridViewRow r in gvExport.Rows)
                    {
                        if (r.RowType == DataControlRowType.DataRow)
                        {
                            for (int columnIndex = 0; columnIndex < r.Cells.Count; columnIndex++)
                            {
                                r.Cells[columnIndex].Attributes.Add("class", "text");
                            }
                        }
                    }
                    //(end): require for date format issue

                    gvExport.RenderControl(htw);
                    //(start): require for date format issue
                    System.Text.StringBuilder style = new System.Text.StringBuilder();
                    style.Append("<style>");
                    style.Append("." + "text" + " { mso-number-format:" + "\\@;" + " }");
                    style.Append("</style>");
                    response.Clear();
                    Response.Buffer = true;
                    //response.Charset = "";
                    //response.Write(sw.ToString());
                    Response.Write(style.ToString());
                    Response.Output.Write(sw.ToString());
                    Response.Flush();
                    //(end): require for date format issue
                    try
                    {
                        response.End();
                    }
                    catch (Exception err)
                    {

                    }
                    //HttpContext.Current.ApplicationInstance.CompleteRequest();
                }
            }
        }

答案 2 :(得分:0)

  

DataTable到Excel通过响应对象导出

一种简单的方法是将我的免费C#类添加到您的项目中,然后添加一行代码,以调用它的“CreateExcelDocument”函数:

DataTable dt = CreateSampleData();
string excelFilename = "C:\\Sample.xlsx";
CreateExcelFile.CreateExcelDocument(ds, excelFilename);

就是这样!

详细信息(可免费下载的源代码和示例项目):

Export to Excel C# class

我的库使用免费的 Microsoft OpenXML 库(我的下载中也提供)来编写文件,因此您不必使用重量级VSTO库,也不必在服务器上安装Excel

此外,它创建了一个真正的.xlsx文件,而不是将数据流写入逗号分隔文本文件的其他方法,但将其命名为.xls文件。