通过下载定制的excel模板,在excel模板上添加数据实现对数据的批量上传于修改,
获取excel内容返回DataTable,再DataTable中验证处理上传的数据保存到数据库,代码如下
using System;
using System.Collections.Generic;using System.Linq;using System.Web;using System.Data;using System.Data.OleDb;using System.IO;namespace ExcelDemo{
public class Excel {public Excel()
{ // // TODO: 在此处添加构造函数逻辑 // } static OleDbConnection GetConnection(string path) { var strConn = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=Excel 8.0;", path); var conn = new OleDbConnection(strConn); conn.Open(); return conn; } /// /// 获取Excel的表名[Sheet1$] /// /// /// /// Excel的路径 /// DataTable public static DataTable GetExcelTableName(string path) { var conn = GetConnection(path); var dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); conn.Close(); return dt; }/// <summary>
/// 根据excel工作表名获取内容 /// </summary> /// <param name="tableName">表名</param> /// <param name="path">文件路径</param> /// <returns>DataTable</returns> public static DataTable GetExcelTable(string tableName, string path) { var sql = string.Format("SELECT * FROM [{0}]", tableName); var conn = GetConnection(path); var myCommand = new OleDbDataAdapter(sql, conn); var myDataSet = new DataSet(); myCommand.Fill(myDataSet); return myDataSet.Tables[0]; } /// <summary> /// 删除文件 /// </summary> /// <param name="path"></param> public static void DeleteFile(string path) { try { File.Delete(path); } catch (Exception e) { throw e; } } /// <summary> /// 流式下载文件 /// </summary> public static void DownLoadFile() { string fileName = "学员上传模板.xlsx";//客户端保存的文件名string filePath = HttpContext.Current.Server.MapPath("File/Temp/上传模板.xlsx");//路径 //以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length]; fs.Read(bytes, 0, bytes.Length);
fs.Close();
HttpContext.Current.Response.ContentType = "application/octet-stream";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));//通知浏览器下载文件而不是打开
HttpContext.Current.Response.BinaryWrite(bytes);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.End();
} }}