转换数据表不可逆?

发布于 2024-12-28 22:45:27 字数 2584 浏览 4 评论 0原文

我正在尝试将 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 作为 .xls (2003) 格式。但不知怎的,它还是发生了。

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

我想我做错了什么。所以我希望有人能够在这里帮助我。

I am trying to convert a DataTable into XLS file.
Code below

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();

This code seems fine. It produced an xls file. And it can be opened correctly. However I tried to reverse engineer this process. In short, converting back this particular xls file into a datatable. Code below:

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);      
        }

This code produced error. It says:

External file format not supported

I noticed this error is similar when you use the wrong OLEDB provider. But in my case there is supposed to be no problem as I am using Microsoft.Jet.OLEDB.4.0 for .xls (2003) format. But somehow it happened still.

This code somehow works for any other .xls file that I tested. It doesn't work only to the files that produced from conversion using the #Snippet1. However supposed I produced a file using #Snippet1 and then I copy all the cells into a new .xls file. The #Snippet2 will work against this new file. In short, only file directly produced from #Snippet1 that won't work.

I figured I did something wrong. So I hope that somebody might be able to help me here.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

冬天旳寂寞 2025-01-04 22:45:27

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

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

或者,您可以生成一个 .csv 文件,并仍然保留 Excel 内容类型,以便 Excel 打开它,但您会丢失格式。然后您导入可以检查扩展名以将其读取为 Excel 或平面文本。

Your Excel output snippet OS not generating an Excel file. It is generating an html table and setting the content type to tell the computer to open it with Excel.

You will need to use a library to generate a real excel file or use the excel data interop (there are plenty of articles in both) in order to consume it directly.

Alternatively you could generate a .csv file instead and still keep the Excel content-type so excel opens it but you lose formatting. Then you import can check the extension to read it either as excel or flat text.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文