转换DataTable不可逆转?

时间:2012-01-25 02:04:51

标签: c# asp.net datatable oledb xls

我正在尝试将DataTable转换为XLS文件。 代码

Snippet1

Response.Clear();
        Response.Buffer = true;

        Response.AddHeader("content-disposition","attachment;filename=New.xls");
        Response.Charset = "";
        Response.ContentType = "application/vnd.ms-excel";

        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        for (int i = 1; i < gvGridView.HeaderRow.Cells.Count; i++)
        {
            gvGridView.HeaderRow.Cells[i].Text = Table.Columns[i - 1].ColumnName;
        }

        for (int i = 0; i < gvGridView.Rows.Count; i++)
        {
            //Apply text style to each Row
            gvGridView.Rows[i].Attributes.Add("class", "textmode");
        }
        gvGridView.RenderControl(hw);

        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();

这段代码似乎很好。它产生了一个xls文件。它可以正确打开。但是我试图对这个过程进行逆向工程。简而言之,将此特定xls文件转换回数据表。代码如下:

Snippet2

int idx = filen.IndexOf(".");
        string tf = filen.Remove(idx, 4);

        OleDbConnection MyConnection = null;    
        DataSet DtSet = null;    
        OleDbDataAdapter MyCommand = null; 
        //Connection for MS Excel 2003 .xls format
        MyConnection = new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0; Data Source='" + path + "';Extended Properties=Excel 8.0;");     
        MyCommand = new System.Data.OleDb.OleDbDataAdapter("select * from [table$]", MyConnection);      
        DtSet = new System.Data.DataSet();       
        MyCommand.Fill(DtSet);        
        dt = DtSet.Tables[0];        
        MyConnection.Close();            
        if (dt.Rows.Count > 0)        
        {            
            theGridView.DataSource = dt;           
            theGridView.DataBind();       
        }        
        if(System.IO.File.Exists(path))       
        {            
            System.IO.File.Delete(path);      
        }

此代码产生错误。它说:

  

不支持外部文件格式

当您使用错误的OLEDB提供程序时,我注意到此错误类似。但在我的情况下应该没有问题,因为我使用Microsoft.Jet.OLEDB.4.0 for .xls(2003)格式。但不知怎的,它仍然发生了。

此代码以某种方式适用于我测试过的任何其他.xls文件。 它不仅适用于使用#Snippet1 转换产生的文件。但是假设我使用#Snippet1生成了一个文件,然后将所有单元格复制到一个新的.xls文件中。 #Snippet2将对这个新文件起作用。简而言之,只有#Snippet1直接生成的文件才能生效。

我认为我做错了什么。所以我希望有人可以在这里帮助我。

1 个答案:

答案 0 :(得分:1)

您的Excel输出代码段操作系统未生成Excel文件。它正在生成一个html表并设置内容类型以告诉计算机使用Excel打开它。

您需要使用库来生成真实的Excel文件或使用excel数据互操作(两者中有大量文章)才能直接使用它。

或者您可以生成.csv文件而仍保留Excel内容类型,因此excel会打开它,但您会丢失格式。然后导入可以检查扩展名以将其读取为excel或flat text。