方式1:前端读取excel文件流传入后台,后端解析成DataTable,然后将数据插入数据库
本文中使用的excel模板:
[excel表格中列名与数据库中对应,Excel表格中的列可以自定义列名及列数,与后文中DataTable中定义的列数保持一致]
前端代码:
上 传:
格式:.xlxs
js函数(用户点击上传,触发importExp函数):
function importExp() {
var formData = new FormData();
var name = $("#upfile").val();
formData.append("file", $("#upfile")[0].files[0]);
formData.append("name", name);
if (isNull(formData)) {
$.messager.alert("系统提示", "未选择导入文件!", "warning");
return;
}
$.ajax({
type: "POST",
url: "ashx/importExce.ashx",
data: formData,
processData: false, // 不处理数据
contentType: false,
success: function (data) {
$.messager.alert("导入成功", " ");
},
error: function (error) {
$.messager.alert(JSON.stringify(error));//可以加入需要抛出的异常
}
})
}
后端C#代码(读取excel文件流,并解析数据):
public void ProcessRequest(HttpContext context)
{
JsonData data = new JsonData();
System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
BinaryReader reader = new BinaryReader(s);
string fileclass = "";
try
{
for (int i = 0; i < 2; i++)
{
fileclass += reader.ReadByte().ToString();
}
if(fileclass=="4545")(这里我读取到的excel是4545)
{
string fileType = fileclass;
DataTable dt = new DataTable();
using (ExcelPackage pck = new ExcelPackage(s))
{
ExcelWorksheet ws = pck.Workbook.Worksheets[1];
int minColumnNum = ws.Dimension.Start.Column;//工作区开始列
int maxColumnNum = ws.Dimension.End.Column; //工作区结束列
int minRowNum = ws.Dimension.Start.Row; //工作区开始行号
int maxRowNum = ws.Dimension.End.Row; //工作区结束行号
DataColumn vC;
string[] strcolum = { "a", "b"};//对应数据库中的列名
foreach (string i in strcolum)
{
vC = new DataColumn(i, typeof(string));
dt.Columns.Add(vC);
}
if (maxRowNum > 200)
{
maxRowNum = 200;
}
for (int n = 2; n <= maxRowNum; n++)
{
DataRow vRow = dt.NewRow();
for (int m = 1; m <= maxColumnNum; m++)
{
vRow[m - 1] = ws.Cells[n, m].Value;
}
dt.Rows.Add(vRow);
}
}
if (!insertIntodb(dt))
{
data["error"] = "import excel error";
}
data["message"] = "import excel success";
}
}
catch (Exception)
{
throw;
}
finally
{
context.Response.Write(data.ToJson());
}
}
上面处理函数中用到的insertIntodb函数:
public bool insertIntodb(DataTable dt)
{
try
{
using (DbManager dbm = new DbManager("数据库对象"))
{
foreach (DataRow dr in dt.Rows)
{
JsonData jd = new JsonData();
string strsql = string.Empty;
string stra= dr["a"].ToString();
string strb= dr["b"].ToString();
JsonData jdlist = new JsonData();
jdlist.SetJsonType(JsonType.Array);
using (DbManager db = new DbManager("sinew"))
{
if (a != "" || b != "" )
{
strsql = "insert into [Table]() values(stra,strb)";
dbm.SetCommand(strsql);
dbm.ExecuteNonQuery();
}
}
}
}
return true;
}
catch
{
return false;
}
}
方式2:通过前端读取文件路径,传入后台,解析excel文件后,将数据逐条插入数据库中:
前端js:
function importExp() {
var filedata = $("input[name=upfil]")[0].files[0];
var filePath = filedata.filePath();//此处需验证,如果读不到文件路径,请自行去查找获取绝对路径方法,在这里不累赘了
var postdata = { "datatype": "importExce", "path": filePath };
if (isNull(formData)) {
$.messager.alert("系统提示", "未选择导入文件!", "warning");
return;
}
$.ajax({
type: "POST",
url: "ashx/getdata.ashx",
data: JSON.stringify(postdata),
contentType: "application/json; charset=utf-8",
dataType: "json",//数据格式为json格式
success: function (data) {
$.messager.alert("导入成功", " ");
},
error: function (error) {
$.messager.alert(JSON.stringify(error));
}
})
}
后台代码:
public void ProcessRequest(HttpContext context)
{
JsonData data = new JsonData();
try
{
System.IO.Stream s = System.Web.HttpContext.Current.Request.InputStream;
byte[] b = new byte[s.Length];
s.Read(b, 0, (int)s.Length);
string QueryString = Encoding.UTF8.GetString(b);
QueryString = System.Web.HttpUtility.UrlDecode(QueryString, System.Text.Encoding.GetEncoding("utf-8"));
JsonData jd = JsonMapper.ToObject(QueryString);
string datatype = jd["datatype"].ToString();
switch (datatype)
{
case "importExce":
DataTable dt = Getexcel(jd["path"].ToString());
if(!insertIntodb(dt))
{
data["error"] = "import excel error";
}
data["message"] = "import excel success";
break;
}
}
catch (Exception ex)
{
data["error"] = ex.ToString();
}
finally
{
context.Response.Write(data.ToJson());//json数据返回前端
}
}
第二种处理方式中的Getexcel函数:
///
/// 根据路径获取要导入的excel文件
///
///
///
private DataTable Getexcel(string param)
{
DataTable vTable = new DataTable();
FileInfo existingFile = new FileInfo(param);
try
{
ExcelPackage package = new ExcelPackage(existingFile);
int vSheetCount = package.Workbook.Worksheets.Count; //获取总Sheet页
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];//选定 指定页
int maxColumnNum = worksheet.Dimension.End.Column;//最大列
int minColumnNum = worksheet.Dimension.Start.Column;//最小列
int maxRowNum = worksheet.Dimension.End.Row;//最小行
int minRowNum = worksheet.Dimension.Start.Row;//最大行
DataColumn vC;
string[] strcolum = { "a", "b"};//对应数据库中的列名
foreach (string i in strcolum)
{
vC = new DataColumn(i, typeof(string));
vTable.Columns.Add(vC);
}
if (maxRowNum > 200)
{
maxRowNum = 200;
}
for (int n = 2; n <= maxRowNum; n++)
{
DataRow vRow = vTable.NewRow();
for (int m = 1; m <= maxColumnNum; m++)
{
vRow[m - 1] = worksheet.Cells[n, m].Value;
}
vTable.Rows.Add(vRow);
}
}
catch (Exception vErr)
{
//MessageBox.Show(vErr.Message);
}
return vTable;
}
后面数据库插入的函数同方式一中的insertIntodb函数