C# Form 到 OfficeOpenXMml 文件 I/O 写入错误

问题描述 投票:0回答:1

我正在尝试从 C# 表单创建并写入 xlsx 文件。

private async void saveButton_Click(object sender, EventArgs e)
{
   //variables are pulled from the form on save button click
   PullRecord record = new PullRecord
   WellName = wellNametextBox.Text,
   dateFinished = dateFinishedTimePicker.Value.ToShortDateString()
   };
{ 
{


using (FileStream fs = File.Open("C:\\Users\\4ndrocles\\Desktop\\Pulling Reports\\output.xlsx", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite))  
// opening file to read with file location 

    try
    {
        ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
         
         using (ExcelPackage package = new ExcelPackage(new FileInfo("C:\\Users\\4ndrocles\\Desktop\\Pulling Reports\\output.xlsx")))
        {
            // add a new worksheet to the empty workbook with the name created from wellname and date finished
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add($"{record.WellName} - {record.dateFinished}");
            
            //Add the headers
            worksheet.Cells[1, 1].Value = "Well Name";
            worksheet.Cells[1, 3].Value = record.WellName;
            worksheet.Cells[6, 1].Value = "Date Finished";
            worksheet.Cells[6, 3].Value = record.dateFinished;
            package.Save();
                            MessageBox.Show("File Saved");
                        }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                        MessageBox.Show("Error" + ex);
                    }
                }
            }
            catch (FileNotFoundException)
            {                                       
                MessageBox.Show("File does not exist.");
            }

错误:

当 output.xlsx 文件存在时,即使没有通过进程监视器打开文件进行验证,我也会收到此错误

IOException: The process cannot access the file 'C:\Users\4ndrocles\Desktop\Pulling Reports\output.xlsx' because it is being used by another process.

当文件夹中没有output.xlsx 文件时,我收到错误

'Could not find file 'C:\Users\4ndrocles\Desktop\Pulling Reports\output.xlsx'
c# excel xlsx system.io.file
1个回答
0
投票

您打开一个文件流

fs
,但随后使用 ExcelPackage 的构造函数,该构造函数接受 FileInfo,因此也将打开该文件。这会导致异常

IOException:该进程无法访问文件“file”,因为它正在被另一个进程使用。

在这种情况下,“另一个进程”是您自己的程序,但例外情况并不区分这些情况。

请注意,如果您在 Excel 中打开特定的 xlsx 文件,您将得到相同的异常。

要解决此问题,请使用正确的构造函数:

using (ExcelPackage package = new ExcelPackage(fs))
如果还没有文件,您需要创建文件,而不是打开它。 

FileMode 提供了一个值 OpenOrCreate


var file = @"C:\Users\4ndrocles\Desktop\Pulling Reports\output.xlsx"; using (var fs = File.Open(file, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
    
© www.soinside.com 2019 - 2024. All rights reserved.