c#ExportToExcel创建损坏的xlsx文件

时间:2016-04-18 17:19:59

标签: c# excel datagridview

我使用以下库:

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的应用程序文档让我解压缩,但是当我尝试解压缩ISN&#T; T的工作时,它说该文件当前已打开..

4 个答案:

答案 0 :(得分:0)

如果您的第一个列标题被称为“id”,可能会导致问题。您可以尝试将“`”添加到任何名为“id”的列

答案 1 :(得分:0)

问题是我更改了CreateExcelFile.cs

中的部分代码

enter image description here

这与完成它后没有关闭StreamWriter,然后由于这个缺少一堆文本具有相同的效果。我改变了这个代码块b / c没有WindowsBase.dll它没有工作。在引用该DLL并更改代码后,我能够成功将datagridview导出到excel

答案 2 :(得分:0)

我做了类似的东西,也使用了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引用。

答案 3 :(得分:0)

尝试刷新和关闭 HttpResponse 请求。这对我有用。

response.OutputStream.Flush();
response.OutputStream.Close();
response.Flush();
response.Close();