NPOI 入门--上传excel文件并解析

NPOI 2.4.1

首先去设置下webconfig里面上传文件大小的设置,

<httpRuntime targetFramework="4.5" maxRequestLength="102400" executionTimeout="3600"  />,我设置了允许上传最大100M。

话不多说,上MVC 后台代码:

  /// <summary>
        /// 上传文件,上传实体文件
        /// </summary>
        /// <param name="httpfile">与前端post的参数名一致</param>
        [HttpPost]
        public ActionResult UploadExcel(HttpPostedFileBase httpfile)
        {
            ResultModel rm = new ResultModel();
            try
            {
                DataTable dt = null;
                var fileName = httpfile.FileName;
                var hz = fileName.Split(‘.‘);
                if (hz.Count() > 0 & (hz[1].ToString() == "xlsx" || hz[1].ToString() == "xls"))
                {
                    //NPOI操作excel
                    using (Stream stream = httpfile.InputStream)
                    {
                        Stopwatch sw = new Stopwatch();
                        sw.Start();
                        var workbook1 = new XSSFWorkbook(stream);
                        var sheet = workbook1.GetSheetAt(0);//默认获取第1个sheet
                        sw.Stop();
                        TimeSpan t1 = sw.Elapsed;//文件读取耗时
                        /*excel流文件转为datatable*/
                        sw.Restart();
                        dt = RenderFromExcel(sheet, 0);
                        sw.Stop();
                        TimeSpan t2 = sw.Elapsed;//转换datatable耗时
                        LogHelper.Info("条数:"+dt.Rows.Count+",文件读取耗时:" + t1 + ",转换datatable耗时:" + t2);
                        rm.Status = statuslist.成功;
                        rm.ResultMessage = "文件识别成功!";
                    }
                }
                else
                {
                    rm.Status = statuslist.失败;
                    rm.ResultMessage = "未识别文件类型,请上传正确文件格式!";
                    //错误
                }
            }
            catch (Exception ex)
            {
                rm.Status = statuslist.失败;
                rm.ResultMessage = ex.Message;
            }
            JsonResult jr = new JsonResult();
            jr.Data = Json(rm);
            return jr;
        }

上传实体文件

  /// <summary>
        /// excel转为datatable
        /// </summary>
        /// <param name="sheet">需要转换的isheet对象</param>
        /// <param name="headerRowIndex">表头所在行</param>
        /// <returns></returns>
        private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex)
        {
            DataTable table = new DataTable();
            IRow headerRow = sheet.GetRow(headerRowIndex);
            int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
            int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1

            //handling header.
            for (int i = headerRow.FirstCellNum; i < cellCount; i++)
            {
                DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
                table.Columns.Add(column);
            }

            for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
            {
                IRow row = sheet.GetRow(i);
                DataRow dataRow = table.NewRow();
                //第一列如果为空,则不添加至datatable中
                if (row != null & GetCellValue(row.GetCell(0)) != "")
                {
                    for (int j = row.FirstCellNum; j < cellCount; j++)
                    {
                        if (row.GetCell(j) != null)
                            dataRow[j] = GetCellValue(row.GetCell(j));
                    }
                    table.Rows.Add(dataRow);
                }

            }

            return table;
        }

excel流转datatable

        /// <summary>
        /// 获取excel单元格类型以及值
        /// </summary>
        /// <param name="cell"></param>
        /// <returns></returns>
        private static string GetCellValue(ICell cell)
        {
            if (cell == null)
                return string.Empty;
            switch (cell.CellType)
            {
                case CellType.Blank:
                    return string.Empty;
                case CellType.Boolean:
                    return cell.BooleanCellValue.ToString();
                case CellType.Error:
                    return cell.ErrorCellValue.ToString();
                case CellType.Numeric:
                case CellType.Unknown:
                default:
                    return cell.ToString();//This is a trick to get the correct value of the cell. NumericCellValue will return a numeric value no matter the cell value is a date or a number
                case CellType.String:
                    return cell.StringCellValue;
                case CellType.Formula:
                    try
                    {
                        XSSFFormulaEvaluator e = new XSSFFormulaEvaluator(cell.Sheet.Workbook);
                        // HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
                        e.EvaluateInCell(cell);
                        return cell.ToString();
                    }
                    catch
                    {
                        return cell.NumericCellValue.ToString();
                    }
            }
        }

获取单元格类型及赋值

前端代码:

/*上传类型,Stream or File*/
var _type;
/*文件对象*/
var _fileobj;
/*posturl*/
var _posturl;
/*控制的对象*/
var _element = null;
function fileupload(type, fileobj, posturl, element) {
    try {
        console.log("fileupload");
        if (fileobj != null)
            _fileobj = fileobj;
        if (posturl != null)
            _posturl = posturl;
        if (element != null)
            _element = element;
        if (type != null) {
            switch (type) {
                case "Stream":
                    {
                        globalmodal(_element, true);
                        _type = "Stream";
                        var file = fileobj;
                        if (!!file) {
                            var reader = new FileReader();
                            /*客户端读取文件,并发送*/
                            reader.readAsArrayBuffer(file);
                            reader.onload = function (e) {
                                var binary = e.target.result;
                                upload(binary, _posturl);
                            }
                        } else
                            modaldisplay("3", "提示", "文件不能为:" + file);
                        break;
                    }
                case "File":
                    {
                        _type = "File";
                        if (_element != null)
                            globalmodal(_element, true);
                        var formData = new FormData();
                        formData.append("httpfile", fileobj);
                        $.ajax({
                            type: ‘post‘,
                            url: _posturl,
                            // 告诉jQuery不要去处理发送的数据
                            processData: false,
                            // 告诉jQuery不要去设置Content-Type请求头
                            contentType: false,
                            data: formData,
                            success: function (reponse) {
                                globalmodal(_element, false);
                                if (reponse.Data.Status != 1) {
                                    modaldisplay("2", "提示", reponse.Data.ResultMessage);
                                }
                                else {
                                    modaldisplay("1", "提示", reponse.Data.ResultMessage);
                                }

                            }
                        });
                        break;
                    }
                default: {
                    globalmodal(_element, true);
                    modaldisplay("3", "文件类型错误提示", "fileupload方法错误!");
                }
            }
        }
        else {
            modaldisplay("3", "文件类型错误提示", "请填写type!");
        }
    } catch (e) {
        modaldisplay("3", "异常提示", e.message);
    }
    finally {

    }

}
/*发送数据*/
function upload(binary, posturl) {
    try {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", posturl);
        xhr.overrideMimeType("application/octet-stream");
        if (xhr.sendAsBinary) {
            xhr.sendAsBinary(binary);
        } else {
            xhr.send(binary);
        }
        /*回调*/
        xhr.onload = function (e) {
            globalmodal(_element, false);
            if (this.status == 200) {
                var responsedata = JSON.parse(e.target.response);
                modaldisplay("1", "提示", responsedata.Data.ResultMessage);
                /*表示成功*/
            }
            else {
                /*失败*/
                modaldisplay("3", "提示", "文件处理失败!");
            }
        }
    } catch (e) {
        modaldisplay("3", "错误提示", e.message);
    }
}

封装了上传文件的方法

调用:

<div class="row" id="fileuploadmodal">
    <input type="file" id="file2" />
    <input type="button" id="btnupload2" value="上传文件" />
    <input type="button" id="btnuploadstream" value="上传流" />
</div>
<script>
 /*文件上传*/
    $("#btnupload2").on("click", function () {
        var filetype = "File";
        var file = $("#file2")[0].files[0];
        var posturl = "sdm/UploadExcel";
        var element = $("#fileuploadmodal");
        fileupload(filetype, file, posturl, element);
    });
  /*流形式*/
    $("#btnuploadstream").on("click", function () {
        var filetype = "Stream";
        var file = $("#file2")[0].files[0];
        var posturl = "sdm/UploadExcelStrem";
        var element = $("#fileuploadmodal");
        fileupload(filetype, file, posturl, element);
    });
</script>

页面调用

上传7m左右的文件,耗时25S左右,其中23S在读取文件上,想办法优化下。

原文地址:https://www.cnblogs.com/daniel-niu/p/10614356.html

时间: 2024-11-09 05:25:06

NPOI 入门--上传excel文件并解析的相关文章

eclipse中导入jdk源码、SpringMVC注解@RequestParam、SpringMVC文件上传源码解析、ajax上传excel文件

eclipse中导入jdk源码:http://blog.csdn.net/evolly/article/details/18403321, http://www.codingwhy.com/view/799.html. ------------------------------- SpringMVC注解@RequestParam:http://825635381.iteye.com/blog/2196911. --------------------------- SpringMVC文件上传源

js兼容ie获取上传excel文件名称以及大小,绝对路径

/**  *   * @param obj file对象 document.getElementById(elementId);  * @returns  */ function getExcelFileFullPath(obj){ if (obj){ // ie if (window.navigator.userAgent.indexOf("MSIE") >= 1){ obj.select(); return document.selection.createRange().t

js上传Excel文件

一.问题 需要在项目里添加一个上传excel文件的功能,因为其他同样的后台里面有上传文件的功能,第一反应就是想着直接用.了解了一下发现它是利用bootstrap的fileinput实现的,但是我怎么都不能把fileinput插件给加到java的项目里,然后就只能自己用js实现吧.好像也没什么特别的需求. 1)原本的样式不好看,需要和项目一致 2)只上传xls和xlxs的文件 二.代码 <input type="file" id="file" name=&quo

上传Excel文件使用JXL解析

继续昨天的说,昨天说到用fullcalendar日期控件来显示日程,现在有一个需求是读取Excel中的日程信息,然后显示在日历上,继续记录备忘. 一.上传文件 上传文件也困惑了我很久,今天一起记录一下.项目框架是SSH的,所以上传文件就使用了struts2的fileupload,所需要的jar包都在引入struts2的时候引入了,然后就是直接上代码操作了. 1.1 页面 <form id="excelform" action="........." metho

基于Spring MVC实现基于form表单上传Excel文件,批量导入数据

在pom.xml中引入: <!--处理2003 excel--> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.16</version> </dependency> <!--处理2007 excel--> <dependency> <group

网页上传excel文件到服务器,服务端用NPOI解析excel

aspx: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="MyLoad.aspx.cs" Inherits="UpdateAddi_MyLoad" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org

django上传excel文件

def uploadGrade(request): ''' 班级信息导入 :param request: :return: ''' if request.method == 'POST': f = request.FILES.get('file') excel_type = f.name.split('.')[1] if excel_type in ['xlsx','xls']: # 开始解析上传的excel表格 wb = xlrd.open_workbook(filename=None,fil

jQuery+php+ajax+PHPExcel实现上传excel文件导入数据库

项目中需要批量导入数据,感觉这个需求以后也会经常用,必须总结分享下: 引入jquery的第三方表单插件: <scripttype="text/javascript"src="/js/lib/jquery.ajax.form.js"></script> 视图文件:goods_list.ctp(商品列表), <div class="btnimport"> <form class='myupload' acti

复制黏贴上传excel文件到网站

假如有一个excel文件,想把里面的内容传到网站上去. 可以利用JSON.stringify() 把空格和换行等字符转换为 escape sequence.如: 这就转换成了escape sequnence 但这个方法目前只支持到 IE8 Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari Basic support (Yes) 3.5 (1.9.1) 8.0 10.5 4.0