无法打开包,因为FileMode或FileAccess值对c#流无效



我试图在c#中使用此函数加载Excel文件(.xlsx)到Datagrid,我的目标是加载数据以便稍后将其保存到数据库。

public static DataTable GetDataFromExcel(string path, dynamic worksheet)
{
//Save the uploaded Excel file.


DataTable dt = new DataTable();
using (var stream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
{
//Open the Excel file using ClosedXML.
using (XLWorkbook workBook = new XLWorkbook(stream))
{
//Read the first Sheet from Excel file.
IXLWorksheet workSheet = workBook.Worksheet(worksheet);
//Create a new DataTable.
//Loop through the Worksheet rows.
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
//Use the first row to add columns to DataTable.
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
if (!string.IsNullOrEmpty(cell.Value.ToString()))
{
dt.Columns.Add(cell.Value.ToString());
}
else
{
break;
}
}
firstRow = false;
}
else
{
int i = 0;
DataRow toInsert = dt.NewRow();
foreach (IXLCell cell in row.Cells(1, dt.Columns.Count))
{
try
{
toInsert[i] = cell.Value.ToString();
}
catch (Exception ex)
{
}
i++;
}
dt.Rows.Add(toInsert);
}
}
return dt;
}
}
}

不幸的是,我得到了这个异常:

无法打开包,因为FileMode或FileAccess值对流无效

如何避免抛出这个异常?

更新:

Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//Static File From Base Path...........
//Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open(AppDomain.CurrentDomain.BaseDirectory + "TestExcel.xlsx", 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
//Dynamic File Using Uploader...........
Microsoft.Office.Interop.Excel.Workbook excelBook = excelApp.Workbooks.Open(txtFilePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, 0);
Microsoft.Office.Interop.Excel.Worksheet excelSheet = (Microsoft.Office.Interop.Excel.Worksheet)excelBook.Worksheets.get_Item(1); ;
Microsoft.Office.Interop.Excel.Range excelRange = excelSheet.UsedRange;
// I have used excelSheet as workSheet

我总是使用这个(c# 9.0):

FileStream fileStream = new(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

还允许我在打开时读取。

如果你没有使用最新版本的c#,那么使用:

var fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);

最新更新