C# 实现 Excel文件的数据导入

时间:2021-08-07 11:37:22

前台

     <asp:FileUpload ID="fuFile" runat="server" />

后台

    public string GetExcel()
{
string msg = null;
if (this.fuFile.HasFile)
{
var file = this.fuFile.PostedFile;
var extension = Path.GetExtension(file.FileName);
switch (extension)
{
case ".xls":
case ".xlsx":
IWorkbook workbook = null;
try
{
string fileName = "新的文件名,用于存放在服务器" + extension;
file.SaveAs(Path.Combine(Server.MapPath(“excel存放路径”), fileName));
workbook = WorkbookFactory.Create(file.InputStream);
ISheet sheet = workbook.GetSheetAt();
IRow row = null;
for (int i = ; i < sheet.LastRowNum; i++)//第1行开始读
{
row = sheet.GetRow(i);
if (row == null)
{
break;//遇到空行
}
string cellText = row.GetCell() == null ? "" : row.GetCell().ToString(); //获取第一列的数据
}
}
catch (Exception ex)
{
msg = ex.Message;
}
break;
default:
msg = "仅支持.xls或.xlsx格式的Excel。";
}
}
else
{
msg = "请选择文件";
}
return msg;
}