本示例基于NPOI,请先添加NPOI.dll的引用
1、建立一个Excel文件,插入几条测试数据
2、定义一个Import类,用于读取Excel文件,并保存到DataTable
/// <summary>
/// 读取excel ,默认第一行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable();
HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheetAt(0);
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int j = 0; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
}
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = dt.NewRow();
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = row.GetCell(j).ToString();
}
dt.Rows.Add(dataRow);
}
return dt;
}
3、使用Request.Files接收从页面传递的文件参数,用上面的方法读取然后导入到数据库,导入数据库代码请按照自己的要求自行增加
public JsonResult toImport()
{
HttpFileCollection files = System.Web.HttpContext.Current.Request.Files;
if (files.Count == 0)
{
return Json(new { result = "NO", message = "请选择文件" }, "text/html", JsonRequestBehavior.AllowGet);
}
string IsXls = System.IO.Path.GetExtension(files[0].FileName).ToString().ToLower();//System.IO.Path.GetExtension获得文件的扩展名
if (IsXls != ".xls" && IsXls != ".xlsx")
{
return Json(new { result = "NO", message = "只可以选择.xls文件" }, "text/html", JsonRequestBehavior.AllowGet);
}
string filename = DateTime.Now.ToString("yyyymmddhhMMss") + files[0].FileName; //获取Execle文件名 DateTime日期函数
string savePath = Server.MapPath(("~\\upload\\") + filename);//Server.MapPath 获得虚拟服务器相对路径
files[0].SaveAs(savePath); //SaveAs 将上传的文件内容保存在服务器上
DataTable dt = Import(savePath);
DataRow[] dr = dt.Select(); //定义一个DataRow数组
int rowsnum = dt.Rows.Count;
if (rowsnum == 0)
{
return Json(new { result = "NO", message = "Excel表为空表,无数据!" }, "text/html", JsonRequestBehavior.AllowGet);
}
else
{
List<excel.DAL.excel> lex = new List<excel.DAL.excel>();
string error = string.Empty;
for (int i = 0; i < dr.Length; i++)
{
string c1 = dr[i]["1"].ToString().Trim();
string c2 = dr[i]["2"].ToString().Trim();
string c3 = dr[i]["3"].ToString().Trim();
string c4 = dr[i]["4"].ToString().Trim();
string c5 = dr[i]["5"].ToString().Trim();
string c6 = dr[i]["6"].ToString().Trim();
string c7 = dr[i]["7"].ToString().Trim();
string c8 = dr[i]["8"].ToString().Trim();
string c9 = dr[i]["9"].ToString().Trim();
string c10 = dr[i]["10"].ToString().Trim();
//以下执行导入到数据库代码,请自行添加
}
ViewBag.lex = lex;
if (string.IsNullOrEmpty(error))
{
return Json(new { result = "OK", message = "Excle表导入成功" }, "text/html", JsonRequestBehavior.AllowGet);
}
else
{
return Json(new { result = "NO", message = error }, "text/html", JsonRequestBehavior.AllowGet);
}
}
}
需要示例代码的请在下面留言您的邮箱。