gpt4 book ai didi

c# - 使用 NPOI 在 Blazor wasm 中读取 Excel 文件

转载 作者:行者123 更新时间:2023-12-04 20:08:52 26 4
gpt4 key购买 nike

以下代码在 PC 上运行的 .NET Core 应用程序中运行良好。该代码加载一个 excel 文件并使用 NPOI 库读取它。

public void ReadExcel()
{
DataTable dtTable = new DataTable();
List<string> rowList = new List<string>();
ISheet sheet;
using (var stream = new FileStream("Test.xlsx", FileMode.Open))
{
stream.Position = 0;
XSSFWorkbook xssWorkbook = new XSSFWorkbook(stream);
sheet = xssWorkbook.GetSheetAt(0);
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
if (cell == null || string.IsNullOrWhiteSpace(cell.ToString())) continue;
{
dtTable.Columns.Add(cell.ToString());
}
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
if (row == null) continue;
if (row.Cells.All(d => d.CellType == CellType.Blank)) continue;
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
if (!string.IsNullOrEmpty(row.GetCell(j).ToString()) && !string.IsNullOrWhiteSpace(row.GetCell(j).ToString()))
{
rowList.Add(row.GetCell(j).ToString());
}
}
}
if (rowList.Count > 0)
dtTable.Rows.Add(rowList.ToArray());
rowList.Clear();
}
}
return JsonConvert.SerializeObject(dtTable);
}
我想在我的 Blazor 应用程序中使用此代码,以便能够从浏览器读取 Excel 文件。我可以使用 InputFile 组件来获取文件:
<InputFile OnChange="GetFile"/>
问题是如何将上传的文件作为流传递给 ReadExcel 函数?所以它应该是这样的:
public async Task GetFile(InputFileChangeEventArgs e) //get excel file
{

stream = e.File.OpenReadStream(); //need a stream here that ReadExcel() can use!

ReadExcel();
}
如果我在 ReadExcel 函数中使用上述流而不是它拥有的流,则代码不起作用。形成这个流的正确方法是什么,以便 ReadExcel 可以使用它而不是现在的那个?
谢谢,
阿姆贾德。

最佳答案

我认为主要问题是 ReadStream 不可搜索(CanSeek == false)。
您可以将其复制到 MemoryStream,但请注意大小限制。

public async Task GetFile(InputFileChangeEventArgs e) //get excel file
{
var stream1 = e.File.OpenReadStream(); //need a stream here that ReadExcel() can use!
var stream2 = new MemoryStream();
await stream1.CopyToAsync(stream2);
stream1.Close();

ReadExcel(stream2);
}

关于c# - 使用 NPOI 在 Blazor wasm 中读取 Excel 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68474677/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com