C#导入Excel

来源:互联网 发布:js给输入框赋值 编辑:程序博客网 时间:2024/06/11 15:03

MVC的网站做的导入,其他模式看情况修改吧
项目用的一些东西这里用不到,所以就捡重点的代码列在下边,如果直接复制此代码出错,稍微修改下再用

前端html

使用form表单提交
主要提交的数据:
1. Excel的路径
2. 需要导入的Excel的sheet的名称,此方法需要根据sheet名称逐个导入,没做批量
代码:

<form action="~/Default/InportData" enctype="multipart/form-data">    Excel表的Sheet名称:<input type="text" value="Sheet1" name="sheet" />    文件路径:<input type="text" value="C:\Users\Administrator\Desktop\2017-5-24\" name="path2" id="path2" style="width:700px" /> (备用)    <br><br><br>    <a href="javascript:;" class="a-upload">        <input type="file" name="path" id="path2">浏览...    </a>    <button type="submit" class="btn btn-warning" style="margin-top:-25px;height:30px" onclick="ShowWaitFrm()">上传</button></form>

class样式,此处没啥用,就是为了好看点

.file{ position:absolute; top:0; right:80px; height:24px; filter:alpha(opacity:0);opacity: 0;width:260px }.a-upload {    padding: 4px 10px;    height: 30px;    line-height: 20px;    position: relative;    cursor: pointer;    color: white;    background: DeepSkyBlue;    border: 1px solid #ddd;    border-radius: 4px;    overflow: hidden;    display: inline-block;    *display: inline;    *zoom: 1}.a-upload  input {    position: absolute;    font-size: 100px;    right: 0;    top: 0;    opacity: 0;    filter: alpha(opacity=0);    cursor: pointer}.a-upload:hover {    color: #444;    background: #eee;    border-color: #ccc;    text-decoration: none}

后台代码

        /// <summary>        /// 插入数据        /// </summary>        /// <param name="path"></param>        /// <returns></returns>        public ActionResult InportData(string path,string path2,string sheet = null)        {            path = ValidatePath(path, path2);            DataTable dt = ExcelData.GetExcelDatatable(path,sheet);            InportxcelData(dt);            return RedirectToAction("Index", "Default");        }

获取DataTable

        /// <summary>        /// Excel数据导入Datable        /// </summary>        /// <param name="fileUrl"></param>        /// <param name="table"></param>        /// <returns></returns>        public static DataTable GetExcelDatatable(string fileUrl, string sheetname = "Sheet1", string table = "mapTable")        {            sheetname = sheetname + "$";            //office2007之前 仅支持.xls            //const string cmdText = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties='Excel 8.0;IMEX=1';";            //支持.xls和.xlsx,即包括office2010等版本的   HDR=Yes代表第一行是标题,不是数据;            const string cmdText = "Provider=Microsoft.Ace.OleDb.12.0;Data Source={0};Extended Properties='Excel 12.0; HDR=Yes; IMEX=1'";            System.Data.DataTable dt = null;            //建立连接            OleDbConnection conn = new OleDbConnection(string.Format(cmdText, fileUrl));            try            {                //打开连接                if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed)                {                    conn.Open();                }                System.Data.DataTable schemaTable = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);                //获取Excel的第一个Sheet名称                string sheetName = null;                for (int i = 0; i < schemaTable.Rows.Count; i++ )                {                    string name = schemaTable.Rows[i]["TABLE_NAME"].ToString().Trim();                    if (name == sheetname) // 这里取到特定sheet名称的那个表                        sheetName = schemaTable.Rows[i]["TABLE_NAME"].ToString().Trim();                }                    // schemaTable.Rows[0]["TABLE_NAME"].ToString().Trim();                //查询sheet中的数据                string strSql = "select * from [" + sheetName + "]";                OleDbDataAdapter da = new OleDbDataAdapter(strSql, conn);                DataSet ds = new DataSet();                da.Fill(ds, table);                dt = ds.Tables[0];                return dt;            }            catch (Exception exc)            {                throw exc;            }            finally            {                conn.Close();                conn.Dispose();            }        }

剩下的就是把DataTable插入到数据库中了,自己根据情况处理吧