Fork me on GitHub

未在本地计算机上注册“Microsoft.ACE.OLEDB.12.0”提供程序。(C# EXCEL导入demo)

1. 安装office包
  https://www.microsoft.com/zh-cn/download/confirmation.aspx?id=13255

2.需要在相应的IIS应用程序池启用32位应用程序

3.代码

//前台
<script language="javascript">
        $(document).ready(function () {
            $('#ImportExcel').on('click', function (e) {
                console.log($(this).next().attr("data-id"));
                $(this).next().trigger('click');

            })
        })
        function Upload(obj) {
            var file = obj.files[0];
            var formData = new FormData();
            formData.append('imgFile', file);
            formData.append('type', "carCheckUpload");
            $.ajax({
                url: "/ajax/ajax_caruseexport.ashx",
                type: "post",
                data: formData,
                contentType: false,
                processData: false,
                mimeType: "multipart/form-data",
                success: function (data) {
                    var jsondata = $.parseJSON(data);
                    console.log(jsondata);
                    alert('导入成功');
                    window.location.reload();
                },
                error: function (data) {
                    alert("上传失败");
                }
            });
        }
    </script>

<div class="lf">
                            <div class="div1" style="margin-left: 15px;">
                                <a href="/Upload/公车检查台账导入表.xls">模板下载</a>
                            </div>
                            <div class="div1" style="margin-left: 15px;">
                                <a id="ImportExcel">公车检查台账导入</a>
                                <input style="display: none;" type="file" onchange="Upload(this)" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel" />
                            </div>
                            
                        </div>
//后台处理程序
<%@ WebHandler Language="C#" Class="ajax_caruseexport" %>

using System;
using System.Collections;
using System.Web;
using System.IO;
using System.Globalization;
using LitJson;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;
using System.Data;
using System.Data.OleDb;
using System.Data.Linq.SqlClient;
using System.Linq;

public class ajax_caruseexport : IHttpHandler, System.Web.SessionState.IRequiresSessionState
{
    private HttpContext context;
    BaseService bs = new BaseService();

    public void ProcessRequest(HttpContext context)
    {
        this.context = context;
        int maxSize = 1000000000;
        String savePath = "/Upload/" + DateTime.Now.ToString("yyyy") + "/" + DateTime.Now.ToString("yyyyMM") + "/";

        Hashtable extTable = new Hashtable();
        extTable.Add("file", "doc,docx,xls,xlsx,ppt,pptx,txt,zip,rar,gz,bz2");
        HttpPostedFile imgFile = context.Request.Files["imgFile"];

        if (imgFile == null) showError("请选择文件。");
        String dirName = context.Request.QueryString["dir"];
        if (String.IsNullOrEmpty(dirName)) dirName = "file";
        if (!extTable.ContainsKey(dirName)) showError("目录名不正确。");
        String fileName = imgFile.FileName;
        String fileExt = Path.GetExtension(fileName).ToLower();

        if (imgFile.InputStream == null || imgFile.InputStream.Length > maxSize) showError("上传文件大小超过限制。");
        if (String.IsNullOrEmpty(fileExt) || Array.IndexOf(((String)extTable[dirName]).Split(','), fileExt.Substring(1).ToLower()) == -1) showError("上传文件扩展名是不允许的扩展名。\n只允许" + ((String)extTable[dirName]) + "格式。");

        if (!Directory.Exists(context.Server.MapPath(savePath))) Directory.CreateDirectory(context.Server.MapPath(savePath));

        String newFileName = "meeting_" + DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
        String fileUrl = savePath + newFileName;

        imgFile.SaveAs(context.Server.MapPath(fileUrl));
        if (!(IsAllowedExtension(fileUrl))) showError("非法文件!请上传正确的文件!");
        var msg = ImportUser(context, context.Server.MapPath(fileUrl));

        Hashtable hash = new Hashtable();
        hash["error"] = 0;
        hash["url"] = fileUrl;
        hash["msg"] = msg;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    private void showError(string message)
    {
        Hashtable hash = new Hashtable();
        hash["error"] = 1;
        hash["message"] = message;
        context.Response.AddHeader("Content-Type", "text/html; charset=UTF-8");
        context.Response.Write(JsonMapper.ToJson(hash));
        context.Response.End();
    }

    //文件真实性判断
    private bool IsAllowedExtension(string FileUrl)
    {
        System.IO.FileStream fs = new System.IO.FileStream(context.Server.MapPath(FileUrl), System.IO.FileMode.Open, System.IO.FileAccess.Read);
        System.IO.BinaryReader r = new System.IO.BinaryReader(fs);
        string fileclass = "";
        byte buffer;
        buffer = r.ReadByte();
        fileclass = buffer.ToString();
        buffer = r.ReadByte();
        fileclass += buffer.ToString();
        r.Close();
        fs.Close();
        /* 文件扩展名说明
        *7173    gif 
        *255216   jpg
        *13780    png
        *6677    bmp
         */
        Dictionary<String, String> ftype = new Dictionary<string, string>();
        //添加允许的文件类型
        ftype.Add("7173", "gif");
        ftype.Add("255216", "jpg");
        ftype.Add("13780", "png");
        ftype.Add("6677", "bmp");
        ftype.Add("8297", "rar");
        ftype.Add("208207", "doc");

        ftype.Add("3780", "pdf");
        ftype.Add("8075", "xlsx");


        if (ftype.ContainsKey(fileclass))
        {
            return true;
        }
        else
        {
            System.IO.File.Delete(context.Server.MapPath(FileUrl));
            return false;
        }

    }

    /// <summary>
    /// 导入通讯录
    /// </summary>
    /// <param name="context"></param>
    /// <param name="filePath"></param>
    /// <returns></returns>
    public string ImportUser(HttpContext context, string filePath)
    {
        var result = "";
        string type = context.Request["type"];
        if (type == "carCheckUpload")
        {
            DataTable dt = ExcelToDataTable(filePath);
            BaseHelper.WriteLogs("ImportCarCheck", Newtonsoft.Json.JsonConvert.SerializeObject(dt) + "--" + dt.Rows.Count, "Import");
            if (dt.Rows.Count > 3)
            {
                var firstRow = dt.Rows[1];  //第一行是检查人数据
                DateTime nowTime = DateTime.Now;
                for (int i = 3; i < dt.Rows.Count; i++)
                {
                    CarUseCheckRegistration entity = new CarUseCheckRegistration()
                    {
                        carName = dt.Rows[i][0].ToString(),
                        brand = dt.Rows[i][1].ToString(),
                        linkMan = dt.Rows[i][2].ToString(),
                        linkTel = dt.Rows[i][3].ToString(),
                        company = dt.Rows[i][4].ToString(),
                        terminal = dt.Rows[i][5].ToString(),
                        endTime = dt.Rows[i][6].ToString(),
                        isUsually = dt.Rows[i][7].ToString(),
                        isRegularPark = dt.Rows[i][8].ToString(),
                        remark = dt.Rows[i][9].ToString(),
                        status = 1,
                        createtime = nowTime,
                    };
            //保存
                    BLL_PublicCar.SaveCarUseCheckRegistration(entity);
                }

                ImageInfo imageInfo = new ImageInfo()
                {
                    ClassId = 520,
                    Title = firstRow[3] + "",
                    Content = firstRow[1] + "",
                };
                using (SiteCmsDataContext db = new SiteCmsDataContext())
                {
                    var temp = db.ImageInfo.Where(w => w.ClassId == imageInfo.ClassId).FirstOrDefault();
                    if (temp == null)
                    {
                        db.ImageInfo.InsertOnSubmit(imageInfo);
                        db.SubmitChanges();
                    }
                    else
                    {
                        if (imageInfo.Title.IsNotNullOrEmpty())
                        {
                            temp.Title = imageInfo.Title;
                        }
                        if (imageInfo.Content.IsNotNullOrEmpty())
                        {
                            temp.Content = imageInfo.Title;
                        }
                        temp.ClassId = imageInfo.ClassId;
                        db.SubmitChanges();
                    }
                }
            }
        }
        return result;
    }

    public DataTable ExcelToDataTable(string strExcelFileName)
    {
        string strConn = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + strExcelFileName + ";" + "Extended Properties='Excel 8.0;HDR=NO;IMEX=1';";
        OleDbConnection conn = new OleDbConnection(strConn);
        conn.Open();
        DataSet ds = new DataSet();
        OleDbDataAdapter adapter = new OleDbDataAdapter("select * from [" + GetExcelFirstTableName(strExcelFileName) + "]", strConn);
        adapter.Fill(ds);
        conn.Close();
        return ds.Tables[0];
    }

    public string GetExcelFirstTableName(string excelFileName)
    {
        string tableName = null;
        if (File.Exists(excelFileName))
        {
            using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties=\"Excel 8.0\";Data Source=" + excelFileName))
            {
                conn.Open();
                DataTable dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                tableName = dt.Rows[0][2].ToString().Trim();
            }
        }
        return tableName;
    }


    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

 

posted @ 2022-12-16 15:25  WantRemake  阅读(329)  评论(0编辑  收藏  举报