DataTableをXLSファイルに変換しようとしています。 コードDataTableを不可逆に変換しますか?
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から直接生成されたファイルだけが動作しません。
私は私が何か間違ったことをした考え出しました。だから私は誰かがここで私を助けることができるかもしれないことを願っています。
どうすればいいですか?あなたがしている場合、償いをします。 – rofans91
私は自分でこの問題を解決することができました。あなたの説明は正しいものでした。 .xlsファイルを作成するのは悪い方法でした。 – rofans91