.net 6.0使用nopi 上传excel
时间: 2023-07-21 12:32:07 浏览: 148
在.NET 6.0中,使用nopi来上传Excel文件的步骤与之前版本的ASP.NET基本相同,只需要在项目中引用NPOI库即可。
以下是一个.NET 6.0中使用nopi上传Excel文件的示例代码:
1. 在ASP.NET页面中,添加一个FileUpload控件,用于选择要上传的Excel文件。
```
<form method="post" enctype="multipart/form-data">
<input type="file" name="fileUpload" />
<button type="submit">Upload</button>
</form>
```
2. 在处理文件上传的控制器中,可以使用以下代码来读取Excel文件并将其保存到数据表中:
```
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Data;
using System.IO;
public class ExcelController : Controller
{
[HttpPost]
public IActionResult Upload(IFormFile fileUpload)
{
if (fileUpload != null && fileUpload.Length > 0)
{
string fileName = Path.GetFileName(fileUpload.FileName);
string fileExtension = Path.GetExtension(fileName);
if (fileExtension == ".xls" || fileExtension == ".xlsx")
{
string fileLocation = Path.Combine(Directory.GetCurrentDirectory(), "Upload", fileName);
using (var stream = new FileStream(fileLocation, FileMode.Create))
{
fileUpload.CopyTo(stream);
}
// Create a new Excel document
IWorkbook workbook;
if (fileExtension == ".xls")
{
workbook = new HSSFWorkbook(new FileStream(fileLocation, FileMode.Open));
}
else
{
workbook = new XSSFWorkbook(new FileStream(fileLocation, FileMode.Open));
}
// Get the first worksheet
ISheet sheet = workbook.GetSheetAt(0);
// Create a new DataTable
DataTable dt = new DataTable();
// Loop through each row in the worksheet
for (int i = 0; i <= sheet.LastRowNum; i++)
{
// Get the current row
IRow row = sheet.GetRow(i);
// Create a new DataRow
DataRow dr = dt.NewRow();
// Loop through each cell in the row
for (int j = 0; j < row.LastCellNum; j++)
{
// Get the current cell
ICell cell = row.GetCell(j);
// Add the cell value to the DataRow
if (cell != null)
{
dr[j] = cell.ToString();
}
}
// Add the DataRow to the DataTable
dt.Rows.Add(dr);
}
// Save the DataTable to the database
// ...
// Delete the uploaded Excel file
System.IO.File.Delete(fileLocation);
}
}
return RedirectToAction("Index");
}
}
```
这样就可以使用nopi来上传Excel文件并将其保存到数据表中了。
阅读全文