C# 使用NPOI批量导出

第一次用C#,用C#写一个批量导出Excel功能

1.引用NPOI资源包,有两种方法,可以在VS中直接安装,也可以下载NPOI.DLL文件添加引用

我用的第一种方法,相对来说比较方便

(1).右击解决方案——>管理解决方案的NuGet程序包

C# 使用NPOI批量导出_第1张图片

选择需要用到NPOI项目勾选上并点击安装

(2).使用NPOI导出

这个批量导出的功能是把数据库中数据导出到浏览器下载的位置

由于是Ajax请求批量导出接口,所以不能直接导出到浏览器下载

我是先把文件导出到本地,成功后访问下载导出到本地的Excel接口

 

异步请求代码:

$.ajax({
                url: "/KtdocPrescription/BatchExport.ajax",
                data: { "orgAreaId": orgAreaId, "orgCode": orgCode, "RecordTimef": RecordTimef, "RecordTimet": RecordTimet, "presSource": presSource },
                dataType: "json",
                asycn: false,
                type: "post",
                success: function (data) {
                    mini.unmask(document.body);
                    if (data.data == "out") {
                        mini.alert("数据超过50000条,导出失败!请重新输入搜索条件");
                    } else if (data.data == "fail") {
                        mini.alert("导出失败!");
                    } else {
                        mini.alert("导出成功!");
                        location.href = "/KtdocPrescription/DownloadExcel.ajax?path=" + data.data;
                    }
                },
                error: function (data) {
                    mini.unmask(document.body);
                    mini.alert("系统异常!");
                }
            });

批量导出代码:

            //查询数据库返回数据列表列表
            DataTable dataTable = (DataTable)dtFilled;
            //限制不能超过50000行,插入到Excel可能会内存溢出
            if (dataTable.Rows.Count > 50000)
            {
                return "out";
            }

            //创建一个空表
            DataTable dt = new DataTable("处方信息统计");
            //1.创建空行
            //DataRow dr = dt.NewRow();
            DataColumn dc1 = new DataColumn();
            dc1.ColumnName = "序号";
            dc1.DataType = typeof(int);

            DataColumn dc2 = new DataColumn();
            dc2.ColumnName = "医院名称";
            dc2.DataType = typeof(string);

            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            
            for (int i = 0; i < dataTable.Rows.Count; i++)
            {
                try
                {
                    DataRow dr = dt.NewRow();
                    dt.Rows.Add(dataTable.Rows[i][0].ToString(), dataTable.Rows[i]["ORG_NAME"].ToString());//Add里面参数的数据顺序要和dt中的列的顺序对应
                }
                catch (Exception e)
                {
                    Logger.WriteError(e);
                }
            }

            //设置导出文件路径,临时存放文件
            string path = HttpRuntime.AppDomainAppPath.ToString();

            //设置新建文件路径及名称
            string savePath = path + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "ktdocPrescription.xls";

            bool flag = ExportExcelUtil.TableToExcel(dt, savePath);
            if (flag == true)
            {
                savePath = HttpUtility.UrlEncode(savePath);
                return savePath;
            }
            else
            {
                return "fail";
            }

ExportExcelUtil工具类代码

public class ExportExcelUtil
    {
        /// 
        /// Datable导出成Excel
        /// 
        /// 
        /// 导出路径(包括文件名与扩展名)
        public static bool TableToExcel(DataTable dt, string file)
        {
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(); } else { workbook = null; }
            if (workbook == null) { return false; }
            ISheet sheet = string.IsNullOrEmpty(dt.TableName) ? workbook.CreateSheet("Sheet1") : workbook.CreateSheet(dt.TableName);

            //表头  
            IRow row = sheet.CreateRow(0);
            for (int i = 0; i < dt.Columns.Count; i++)
            {
                ICell cell = row.CreateCell(i);
                cell.SetCellValue(dt.Columns[i].ColumnName);
                if(i != 0)
                {
                    //从第二列开始,设置列宽为20个字符
                    sheet.SetColumnWidth(i, 20 * 256);
                }
            }
            
            //数据  
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                IRow row1 = sheet.CreateRow(i + 1);
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    ICell cell = row1.CreateCell(j);
                    cell.SetCellValue(dt.Rows[i][j].ToString());
                }
            }
            

            //转为字节数组  
            MemoryStream stream = new MemoryStream();
            workbook.Write(stream);
            var buf = stream.ToArray();

            //保存为Excel文件  
            try
            {
                using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buf, 0, buf.Length);
                    fs.Flush();
                    fs.Close();
                    fs.Dispose();
                }
            }
            catch(Exception e)
            {
                Logger.WriteError(e);
                return false;
            }
            //创建一个 IO 流
            MemoryStream ms = new MemoryStream();
            //写入到流
            workbook.Write(ms);
            //转换为字节数组
            byte[] bytes = ms.ToArray();
            //还可以调用下面的方法,把流输出到浏览器下载
            //OutputClient(bytes);

            //释放资源
            bytes = null;
            ms.Close();
            ms.Dispose();

            workbook.Close();
            sheet = null;
            workbook = null;
            return true;
        }

        public static void OutputClient(string path, string fileName)
        {            
            if (!string.IsNullOrEmpty(path))
            {
                //以字符流的形式下载文件
                FileStream fs = new FileStream(path, 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();
                HttpContext.Current.Response.Close();

                FileAttributes attr = File.GetAttributes(path);
                if (attr == FileAttributes.Directory)
                {
                    Directory.Delete(path, true);
                }
                else
                {
                    File.Delete(path);
                }
            }
        }

        /// 
        /// 获取单元格类型
        /// 
        /// 
        /// 
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }
    }

下载刚刚导出的Excel文件

public void DownloadExcel(String path)
        {
            string fileName = "信息表.xls";
            ExportExcelUtil.OutputClient(path, fileName);
        }

在调用的OutputClient方法中提供输出到浏览器下载并删除本地文件。

完!

你可能感兴趣的:(C# 使用NPOI批量导出)