有什么方法可以读取.net core 3.1中的.xlsx扩展文件吗



我在Angular 10中创建了前端,后端在.net core 3.1 中

要求:从前端上传文件(.xlsx(,该文件将在web api中解析,提取的数据将存储在SQL Server中。

使用以下代码从Angular 上传文件

const formData = new FormData();

for (const file of fileToUpload) {
formData.append(file.name, file);
}

我正在web api中获取IFormFileCollection格式的文件。

我无法读取web api中的文件内容。

提前感谢:(

IFormFile postedFile = file[0];
string fileName = Path.GetFileName(postedFile.FileName);
string filePath = Path.Combine(Path.GetTempPath(), fileName);
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
postedFile.CopyTo(stream);
}
string excelConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0;";
using (OleDbConnection connection = new OleDbConnection(excelConnectionString))
{
connection.Open();
if (workBook != string.Empty)
{
//To apply query on the worksheet we need to apply '$' sign after worksheet name
workBook = workBook + "$";
//Select all records from worksheet table                        
OleDbCommand command = new OleDbCommand("Select * FROM [" + workBook + "]", connection);
//Execute the reader
using (OleDbDataReader dr = command.ExecuteReader())
{
try
{
//Create table
sqlConn = new SqlConnection(connString);
sqlConn.Open();
cmd = new SqlCommand { Connection = sqlConn };
// Bulk Copy to created table
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connString))
{
bulkCopyData.DestinationTableName = TABLE_NAME;
bulkCopyData.WriteToServer(dr);
}
}
}
}

最新更新