简体   繁体   English

将数据从DataTable导出到Excel 2007

[英]Export data from DataTable into Excel 2007

Datatable the values are 数据表中的值是

Stalin-- 001 and Micheal-- 002 . 斯大林-001和迈克尔-002。 but generating excel i getting output as 但是生成Excel我得到输出为

在此处输入图片说明

While generating into excel the "0" are not coming.how to solve this type of scenerios. 在生成excel时,“ 0”不会出现。如何解决这种场景。

Code: 码:

if (dt.Rows.Count > 0)
{
    string filename = " ExportedData.xls";
    System.IO.StringWriter tw = new System.IO.StringWriter();
    System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
    DataGrid dgGrid = new DataGrid();
    dgGrid.DataSource = dt;
    dgGrid.DataBind();

    dgGrid.RenderControl(hw);       
    Response.ContentType = "application/vnd.ms-excel";
    Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
    this.EnableViewState = false;
    Response.Write(tw.ToString());
    Response.End();
}

Thats not a problem with your code. 那不是您的代码的问题。 Its an issue with your excel configuration hiding the prefixed zeros. 您的excel配置隐藏了前缀零,这是一个问题。

1.On the Tools menu, click Options, and then click the View tab. 1.在“工具”菜单上,单击“选项”,然后单击“视图”选项卡。

2.Do one of the following: 2.执行以下操作之一:

To display zero (0) values in cells, select the Zero values check box. 要在单元格中显示零(0)值,请选中“零值”复选框。

To display zero values as blank cells, clear the check box. 要将零值显示为空白单元格,请清除该复选框。

You could manually set the content types of your columns in the datatable before linking it to your datagrid. 您可以在将数据表链接到数据网格之前手动设置数据表中列的内容类型。

DataTable dt = new DataTable();
dt.Columns.Add();
dt.Columns[0].DataType = typeof(string);

You could store/update the data in the DataTable to the following format: ="001" 您可以将DataTable中的数据存储/更新为以下格式: =“ 001”

Example: 例:

        DataTable dt = new DataTable();
        dt.Columns.Add("A");
        dt.Columns.Add("B");

        dt.Rows.Add(new object[] { "Name", "No" });
        dt.Rows.Add(new object[] { "Stalin", "=\"001\""});
        dt.Rows.Add(new object[] { "Micheal", "=\"002\"" });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM