Excel.Workbook.SaveAs() 在 C# 中单击“否”进行文件替换时引发异常

本文关键字:文件 替换 异常 SaveAs Workbook 单击 Excel | 更新日期: 2023-09-27 18:33:45

我的小控制台工具尝试读取 excel 文件并根据设置的标准从中创建新的文件。

问题:当存在文件名冲突(文件已经存在同名)时,程序应生成具有唯一名称的文件。但是现在出现一条消息,带有"是/否/取消"消息框以保存文件。如果用户单击"否",则会引发异常。消息如下:

A file named 'D:'sample.xls' already exists in this location. Do you want to replace it? 

例外情况:

A first chance exception of type 'System.Runtime.InteropServices.COMException' occurred in ExcelSplitter.exe
Additional information: Exception from HRESULT: 0x800A03EC

以下行引发异常

xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue); 

代码如下:

    private bool WriteToExcel(String fileName, List<RowEntity> headerRowObj, List<RowEntity> dataRowObj)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook = null;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        int headerRowTotal = 0;
        for (int i = 0; i < headerRowObj.Count; i++)
        {
            for (int j = 0; j < headerRowObj[i].ColumnValues.Count; j++)
            {
                xlWorkSheet.Cells[i + 1, j + 1] = headerRowObj[i].ColumnValues[j].ToString();
            }
            headerRowTotal++;
        }
        for (int i = 0; i < dataRowObj.Count; i++)
        {
            for (int j = 0; j < dataRowObj[i].ColumnValues.Count; j++)
            {
                xlWorkSheet.Cells[headerRowTotal + i + 1, j + 1] = dataRowObj[i].ColumnValues[j].ToString();
            }
        }
        if (IsExcelFileOpen(xlWorkBook))
        {
            errorList.Add(Error.GetError(-7));
            return false;
        }
        else
        {
            xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        }
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();
        ReleaseObject(xlWorkSheet);
        ReleaseObject(xlWorkBook);
        ReleaseObject(xlApp);
        return true;
    }

上述方法在以下方法中调用:

 private int SeparateExcleFiles(int headerLines, int groupOnColumn, string outputPath, string inputFile, FileEntity fileObj, RowEntity rowObj)
    {
        List<RowEntity> headerRowObj = fileObj.RowValues.GetRange(0, headerLines);
        if (rowObj.ColumnValues.Count < groupOnColumn)
        {
            errorList.Add(Error.GetError(-6));
            return -6;
        }
        else
        {
            var dataRows = fileObj.RowValues.GetRange(headerLines, fileObj.RowValues.Count - (headerLines)).GroupBy(re => re.ColumnValues[groupOnColumn - 1]).ToList();
            for (int i = 0; i < dataRows.Count; i++)
            {
                var fileName = String.Format("{0}-{1}{2}", Path.GetFileNameWithoutExtension(inputFile), dataRows[i].Key.ToString(), Path.GetExtension(inputFile));
                var filePath = Path.Combine(outputPath, fileName);
                if (File.Exists(filePath))
                {
                    fileName = GetUniqueFilename(fileName);
                }
                if (WriteToExcel(filePath, headerRowObj, dataRows[i].ToList() as List<RowEntity>))
                {
                    System.Console.WriteLine("Wrote {0}", fileName);
                }
            }
            return 0;
        }
    }

 private bool IsExcelFileOpen(Workbook wBook)
    {
        Excel.Application exApp;
        exApp = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
        try
        {
            exApp.Workbooks.get_Item(wBook);
            return true;
        }
        catch (Exception)
        {
            return false;
        }
    }    

我到底哪里做错了?

Excel.Workbook.SaveAs() 在 C# 中单击“否”进行文件替换时引发异常

你能在

保存部分试试这个吗?

try
{
    xlWorkBook.SaveAs(fileName, Excel.XlFileFormat.xlWorkbookNormal, misValue,     misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
}
catch(Exception e)
{
//BLANK (do nothing)
}

这将允许您处理异常,但如果您不想执行任何操作并且只是不覆盖,只需将处理过程留空即可。

使用异常处理程序会让系统认为您确认了该事件,并让程序继续。