将数据保存在 Excel 文件中 -

发布于 2024-10-16 04:42:04 字数 4921 浏览 9 评论 0原文

我有一个小型应用程序,用户最后可以将结果保存在 Excel 文件中。一切看起来都很好,但几秒钟后,Microsoft Windows 出现通信:“程序 Microsoft Office Excel 停止工作”。好吧——消化它。

如果用户将数据保存为 *.xls 文件,则打开该文件没有问题 - 保存到该文件中的数据是正确的。

如果用户将数据保存为 *.xlsx 文件,则会出现问题。当我尝试打开此文件时,显示消息:“程序 Microsoft Excel 无法打开文件 *.xlsx,因为文件格式或扩展名错误。请检查文件是否已损坏以及文件扩展名是否与其格式正确” 。

我用来将数据保存为 Excel 文件的代码如下:

public void SaveData(ExcelWriter ew)
    {
        SaveFileDialog saveFD = new SaveFileDialog();

        saveFD.InitialDirectory = "C:\\users\\Documents";
        saveFD.FileName = this._saveExcelFileName;
        saveFD.Filter = "excel 97-03(*.xls)|*.xls|excel 2007 (*.xlsx)|*.xlsx";
        saveFD.FilterIndex = 2;
        saveFD.RestoreDirectory = true;

        if (saveFD.ShowDialog() == DialogResult.OK)
        {
            try
            {
                this._saveExcelFileName = saveFD.FileName;
                ew.RunExcelWriter(_dt, _saveExcelFileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }


    public void RunExcelWriter(DataTable DataT, string fileName)
    {
        StartExcel();
        GetANewWorkbook();
        GetTheActiveSheet();
        ProcessTheDataTable(DataT);
        SaveTheSheet(fileName);
        Clean();
    }

private void StartExcel()
    {
        // Start Excel and get Application object.
        oXL = new Excel.Application();
        // Set some properties
        oXL.Visible = true;
        oXL.DisplayAlerts = false;
    }

    private void GetANewWorkbook()
    {
        // Get a new workbook.
        oWB = oXL.Workbooks.Add(Missing.Value);
    }

    private void GetTheActiveSheet()
    {
        oSheet = (Excel.Worksheet)oWB.ActiveSheet;
        oSheet.Name= "Wyniki";
    }

    private void ProcessTheDataTable(DataTable DT)
    {

        int rowCount = 1;
        foreach (DataRow dr in DT.Rows)
        {
            rowCount += 1;
            for (int i = 1; i < DT.Columns.Count + 1; i++)
            {
                // Add the header the first time through
                if (rowCount == 2)
                {
                    oSheet.Cells[1, i] = DT.Columns[i - 1].ColumnName;
                    
                }
                oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }
        // Resize the columns
        oRange = oSheet.get_Range(oSheet.Cells[1, 1], oSheet.Cells[rowCount, DT.Columns.Count]);
        oRange.EntireColumn.AutoFit();
        //oRange.Style = oSheet.Cells.Style;      
    }

    private void SaveTheSheet(string FN)
    {
        oSheet = null;
        oRange = null;
        oWB.SaveAs(FN, Excel.XlFileFormat.xlWorkbookNormal,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Excel.XlSaveAsAccessMode.xlShared,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        
        if(oWB.Saved==true)
        {
            MessageBox.Show("Plik został zapisany pomyślnie");
        }
        else
        {
            MessageBox.Show("PLIKU NIE ZAPISANO");
        }
        
        oWB.Close(Missing.Value, Missing.Value, Missing.Value);
        oWB = null;
        oXL.Quit();
    }

如果有人知道为什么会发生这种情况? 非常感谢

更新 1:

建议的答案不起作用。我更改为以下内容:

private void SaveTheSheet(string FN)
    {
        oSheet = null;
        oRange = null;
        oWB.SaveAs(FN, Excel.XlFileFormat.xlXMLSpreadsheet,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Excel.XlSaveAsAccessMode.xlShared,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        
        if(oWB.Saved==true)
        {
            MessageBox.Show("Plik został zapisany pomyślnie");
        }
        else
        {
            MessageBox.Show("PLIKU NIE ZAPISANO");
        }
        
        oWB.Close(Missing.Value, Missing.Value, Missing.Value);
        oWB = null;
        oXL.Quit();
    }

现在,当我保存时,会出现一条消息:

“HRESULT 异常:0x800A03EC

更新 2:

我昨天有点挣扎,在将数据写入 .xlsx 格式时,我设法获得了所需的效果。保存到时.xls 我仍然收到 Microsoft Windows 消息以关闭 Excel 应用程序,但至少(在另一个警告批准后)我可以打开此文件。 下面的代码我用来保存为 .xlsx 格式:

oWB.SaveAs(FN, Excel.XlFileFormat.xlWorkbookDefault,
                Missing.Value, Missing.Value, false, false,
                Excel.XlSaveAsAccessMode.xlNoChange,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);

这是 .xls

                oWB.SaveAs(FN, Excel.XlFileFormat.xlXMLSpreadsheet,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Excel.XlSaveAsAccessMode.xlNoChange,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);

请 - 任何建议都很重要。

I have small application where user at the end can save the results in excel file. Everything looks fine but a few seconds after this appear Microsoft Windows communicate: "Program Microsoft Office Excel stop working". Ok - ingoring it.

If user saves data as *.xls file there is no problem to open this file - data saved into this file are correct.

If user saves data as *.xlsx file ther is a problem. When I try to open this file there show me message: "Program Microsoft Excel can't open file *.xlsx because there is wrong file format or extension. Check if the file was damaged and if the file extension is correct with his format".

The code that I use to save data as excel file are below:

public void SaveData(ExcelWriter ew)
    {
        SaveFileDialog saveFD = new SaveFileDialog();

        saveFD.InitialDirectory = "C:\\users\\Documents";
        saveFD.FileName = this._saveExcelFileName;
        saveFD.Filter = "excel 97-03(*.xls)|*.xls|excel 2007 (*.xlsx)|*.xlsx";
        saveFD.FilterIndex = 2;
        saveFD.RestoreDirectory = true;

        if (saveFD.ShowDialog() == DialogResult.OK)
        {
            try
            {
                this._saveExcelFileName = saveFD.FileName;
                ew.RunExcelWriter(_dt, _saveExcelFileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }


    public void RunExcelWriter(DataTable DataT, string fileName)
    {
        StartExcel();
        GetANewWorkbook();
        GetTheActiveSheet();
        ProcessTheDataTable(DataT);
        SaveTheSheet(fileName);
        Clean();
    }

private void StartExcel()
    {
        // Start Excel and get Application object.
        oXL = new Excel.Application();
        // Set some properties
        oXL.Visible = true;
        oXL.DisplayAlerts = false;
    }

    private void GetANewWorkbook()
    {
        // Get a new workbook.
        oWB = oXL.Workbooks.Add(Missing.Value);
    }

    private void GetTheActiveSheet()
    {
        oSheet = (Excel.Worksheet)oWB.ActiveSheet;
        oSheet.Name= "Wyniki";
    }

    private void ProcessTheDataTable(DataTable DT)
    {

        int rowCount = 1;
        foreach (DataRow dr in DT.Rows)
        {
            rowCount += 1;
            for (int i = 1; i < DT.Columns.Count + 1; i++)
            {
                // Add the header the first time through
                if (rowCount == 2)
                {
                    oSheet.Cells[1, i] = DT.Columns[i - 1].ColumnName;
                    
                }
                oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
            }
        }
        // Resize the columns
        oRange = oSheet.get_Range(oSheet.Cells[1, 1], oSheet.Cells[rowCount, DT.Columns.Count]);
        oRange.EntireColumn.AutoFit();
        //oRange.Style = oSheet.Cells.Style;      
    }

    private void SaveTheSheet(string FN)
    {
        oSheet = null;
        oRange = null;
        oWB.SaveAs(FN, Excel.XlFileFormat.xlWorkbookNormal,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Excel.XlSaveAsAccessMode.xlShared,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        
        if(oWB.Saved==true)
        {
            MessageBox.Show("Plik został zapisany pomyślnie");
        }
        else
        {
            MessageBox.Show("PLIKU NIE ZAPISANO");
        }
        
        oWB.Close(Missing.Value, Missing.Value, Missing.Value);
        oWB = null;
        oXL.Quit();
    }

If anyone knows why this happens?
Many thanks in advance

Update 1:

The suggested answer didn't work. I change to the following:

private void SaveTheSheet(string FN)
    {
        oSheet = null;
        oRange = null;
        oWB.SaveAs(FN, Excel.XlFileFormat.xlXMLSpreadsheet,
            Missing.Value, Missing.Value, Missing.Value, Missing.Value,
            Excel.XlSaveAsAccessMode.xlShared,
            Missing.Value, Missing.Value, Missing.Value,
            Missing.Value, Missing.Value);
        
        if(oWB.Saved==true)
        {
            MessageBox.Show("Plik został zapisany pomyślnie");
        }
        else
        {
            MessageBox.Show("PLIKU NIE ZAPISANO");
        }
        
        oWB.Close(Missing.Value, Missing.Value, Missing.Value);
        oWB = null;
        oXL.Quit();
    }

Now when I saving there is a meesage:

"Exception from HRESULT: 0x800A03EC

Update 2:

I struggled a little bit yesterday and I managed to get the desired effect when writing data to the .xlsx format. When saving to .xls I still get the Microsoft Windows message to close the excel application, but at least (after the approval of another warning) I can open this file.
Below code which I'm using to saving to .xlsx format:

oWB.SaveAs(FN, Excel.XlFileFormat.xlWorkbookDefault,
                Missing.Value, Missing.Value, false, false,
                Excel.XlSaveAsAccessMode.xlNoChange,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);

Here is to .xls

                oWB.SaveAs(FN, Excel.XlFileFormat.xlXMLSpreadsheet,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                Excel.XlSaveAsAccessMode.xlNoChange,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);

Please - any advice is important.

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

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

发布评论

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

评论(2

挽你眉间 2024-10-23 04:42:04

就我而言,也可以使用 Excel.XlFileFormat.xlWorkbookDefaultExcel.XlFileFormat.xlOpenXMLWorkbook

 oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

 oWB.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

In my case aslo works Excel.XlFileFormat.xlWorkbookDefault and Excel.XlFileFormat.xlOpenXMLWorkbook

 oWB.SaveAs(fileName, Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);

or

 oWB.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookDefault, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
春庭雪 2024-10-23 04:42:04

另存为 .xslx 时,尝试使用 Excel.xlXMLSpreadsheet 而不是 Excel.XlFileFormat.xlWorkbookNormal

When saving as an .xslx, try using Excel.xlXMLSpreadsheet instead of Excel.XlFileFormat.xlWorkbookNormal

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