[英]c# ExportToExcel creates corrupted xlsx file
我正在使用以下庫:
http://mikesknowledgebase.azurewebsites.net/pages/CSharp/ExportToExcel.htm
這是我的代碼:
private void exportExcelBtn_Click(object sender, EventArgs e)
{
if (dataGridView1.Rows.Count == 0)
{
MessageBox.Show("There's nothing to export", "Info", MessageBoxButtons.OK);
return;
}
DataTable save = Utilities.DataGridView2DataTable(dataGridView1, "TestingReport");
string outputFile = Utilities.saveDoc(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), save);
if (outputFile != null)
{
DialogResult opt = MessageBox.Show("Export successful. Would you like to view the file?", "Information", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
if (opt == DialogResult.Yes)
{
System.Diagnostics.Process.Start(outputFile);
}
}
}
我在兩個不同的項目中使用完全相同的代碼,但是在一個項目中,它創建的 excel 文件已損壞/無法讀取。
提取 .xlsx 文件的內容時,我注意到的第一件事是工作項目中存在的[Content_Types].xml
文件不在不工作項目的輸出中。 此外,創建的 workbook.xml 文件都是 0kb,而工作項目文件實際上包含數據。
我試過做Console.WriteLine
。
我還使用此代碼將我的DataGridView
轉換為DataTable
以便將其寫入 excel: https : //www.crealoq.com/solved/how-to-convert-datagridview-to-datatable-using-csharp
我已經通過並添加了Console.WriteLine(...)
來驗證數據實際上是從這個函數返回的,一切看起來都很好。
編輯:
我注意到的唯一區別是,當我單擊按鈕保存 excel,然后選擇不立即查看時,當我解壓縮 excel 文檔時,返回有效 excel 文檔的應用程序讓我解壓縮它,但是當我嘗試解壓縮一個不起作用的文件時,它說該文件當前已打開..
如果您的第一個列標題稱為“id”,則可能會導致問題。 您可以嘗試在任何名為“id”的列前加上“`”
我也用 DataGridView 做了類似的事情。
首先,我從我需要的列中獲取值(在我的情況下它只有 1 列)
List<float> values = new List<float>();
for (int y = 0; y < rows; y++)
valores.Add(float.Parse(valoresMonitoreo[0, y].Value.ToString()));
然后導出函數
private void export()
{
Microsoft.Office.Interop.Excel.Application oXL;
Microsoft.Office.Interop.Excel._Workbook oWB;
Microsoft.Office.Interop.Excel._Worksheet oSheet;
object misvalue = System.Reflection.Missing.Value;
try
{
oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oWB = (Microsoft.Office.Interop.Excel._Workbook)(oXL.Workbooks.Open(libro));
oWB.Sheets[x].Select();
//x is the number of the sheet where you want to save data.
oSheet = (Microsoft.Office.Interop.Excel._Worksheet)oWB.ActiveSheet;
//This goes into a for
oSheet.get_Range(tmp, misvalue).Value2 = values[x]; //tmp is a string, which contains letter and number of the cell "A1". misvalue is an object variable
oWB.Save();
oWB.Close();
oXL.Visible = false;
oXL.UserControl = false;
oXL.Application.Quit();
}
catch(Exception exc){}
}
您必須使用 Microsoft.Office.Interop.Excel 參考。
嘗試刷新和關閉 HttpResponse 請求。 這對我有用。
response.OutputStream.Flush();
response.OutputStream.Close();
response.Flush();
response.Close();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.