Mar*_*ice 6 sql-server excel azure azure-web-app-service
背景
我有一个遗留站点,允许授权用户上传产品数据等的 Excel 电子表格。然后该站点读取 Excel 工作表并将数据解压缩到 SQL 服务器中。这是一个旧站点,它使用 OLE。旧但有效。
这个问题
我最近出版的网站到Azure的应用服务,但是,从Excel读取我的代码的现有部分不工作(如Azure不具有正确的驱动程序)。
这个问题
我很高兴能改写这部分代码,但什么是使用Azure的应用服务从Excel读取正确或推荐的方法呢?我不是在问可能起作用的方法,我只对正确的方法感兴趣。
“推荐”是指:
我已经研究过这个问题,但没有找到一个明确的声明来说明最好的方法。如果您有不同方法的经验或知识,如果您能分享关于最佳方法的结论,我将不胜感激。
应该有很多方法可以实现这一点,这里我列出了 2 种,如下:
1.使用DocumentFormat.OpenXml,这是MS发布的,但有点复杂。演示代码在这里。
2.使用ExcelDataReader,非常简单,并且两者都支持.xls and .xlsx
。你可以参考这篇文章来做(注意IsFirstRowAsColumnNames
属性被放弃了,你可以看我下面的代码进行这个更改)。
我用第二种方法编写了一个演示ExcelDataReader
。出于测试目的,我将 excel 上传到 azure web 应用程序目录,如下所示:
以下是excel内容:
步骤1:创建一个asp.net MVC项目,然后通过nuget包管理器安装最新ExcelDataReader
版本ExcelDataReader.DataSet
。
步骤2:在项目中创建一个ExcelData.cs文件,用于读取excel文件:
步骤3:在ExcelData.cs中编写以下代码:
using ExcelDataReader;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
namespace WebApplication42
{
public class ExcelData
{
string _path;
public ExcelData(string path)
{
_path = path;
}
public IExcelDataReader GetExcelReader()
{
FileStream stream = File.Open(_path, FileMode.Open, FileAccess.Read);
IExcelDataReader reader = null;
try
{
if (_path.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
if (_path.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
return reader;
}
catch (Exception)
{
throw;
}
}
//read the sheets name if you need
public IEnumerable<string> GetWorksheetNames()
{
var reader = this.GetExcelReader();
var workbook = reader.AsDataSet();
var sheets = from DataTable sheet in workbook.Tables select sheet.TableName;
return sheets;
}
//read data in a specified sheet
public IEnumerable<DataRow> GetData(string sheet)
{
var reader = this.GetExcelReader();
var workSheet = reader.AsDataSet(new ExcelDataSetConfiguration()
{
ConfigureDataTable = (_) => new ExcelDataTableConfiguration()
{
//indicates if use the header values
UseHeaderRow = true
}
}).Tables[sheet];
var rows = from DataRow a in workSheet.Rows select a;
return rows;
}
}
}
Run Code Online (Sandbox Code Playgroud)
第四步:在控制器中,调用读取excel方法:
public ActionResult Excels()
{
ViewBag.Message = "the data from excel:";
string data = "";
//your excel path after uploaded, here I hardcoded it for test only
string path = @"D:\home\site\wwwroot\Files\ddd.xls";
var excelData = new ExcelData(path);
var people = excelData.GetData("sheet1");
foreach (var p in people)
{
for (int i=0;i<=p.ItemArray.GetUpperBound(0);i++)
{
data += p[i].ToString()+",";
}
data += ";";
}
ViewBag.Message += data;
return View();
}
Run Code Online (Sandbox Code Playgroud)
第5步:发布到azure后,启动站点并查看结果->读取excel中的所有数据: