Writing to an existing Excel File using c#

て烟熏妆下的殇ゞ 提交于 2019-11-28 22:07:33

The using of File.Create is not appropriate here. It returns a (Blank) FileStream, not an Excel File (Define the path with .xls will not create an Excel File...).

And as you do not close and dispose it, you have an exception when you try to open it because it is already in use (and you will have an exception in any way even if you release it, because you have not create an Excel file at this stage).

So if the workbook exists, you can open it by using oXL.Workbooks.Open. If the workbook does not exist, YOU HAVE to create it by using: oXL.Workbooks.Add() and then you call mWorkBook.SaveAs(...) method to really create it.

oXL = new Microsoft.Office.Interop.Excel.Application();
oXL.Visible = true;
oXL.DisplayAlerts = false;

string path = "D:\\LOG.xls";
if (!File.Exists(path)) 
{
    mWorkBook = oXL.Workbooks.Add;
} 
else
{
    mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false,    Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true,
        false, 0, true, false, false);
}

(Hope the VB=>C# is correct!)

And in your SaveAs method, you will have to set the correct FileFormat if you want to create a specific version of Excel file (again set .xls in the path is not enough...)

Optional Object. The file format to use when you save the file. For a list of valid choices, see the FileFormat property. For an existing file, the default format is the last file format specified; for a new file, the default is the format of the version of Excel being used.

Hope this helps.

If the workbook does not exist, the better way to create one would be as such:

Excel.Workbook newWorkbook = excelApplication.Workbooks.Add();

File.Create() returns an instance of FileStream, which you need to close if you want to access the file. You can change..

    if(!File.Exists(path))
    {
        File.Create (path);
    }

to

    if(!File.Exists(path))
    {
        File.Create (path).Close();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!