码迷,mamicode.com
首页 > 其他好文 > 详细

ExcelPackage导入导出,命名空间一定要是EPPlus

时间:2017-12-26 19:04:27      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:.com   message   summary   excel   tor   line   catch   cell   com   

1.引入EPPlus.dll,旧版的是OfficeOpenXml.dll,最好使用EPPlus
2.调用 string path = UploadExecl(batchUpload.BinaryExcel, "xlsx");,获取上传的xlsx路径
3. 下载Execl
    3.1 如果是<a> 标签的连接,可以将方法直接写在 href上就能直接下载
     <a href="/FangAn/DetailAuditOutPut/" target="_blank" style="color:#fff;"><el-button type="primary">导出Execl</el-button></a>
    后台方法调用:
            byte[] result = GetExcelByte(model);
    返回值为 File();
            return File(result, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", model.OrderName + ".xlsx");

    3.2 如果是js异步操作,需要下载的话:
        后台方法调用:
         byte[] result = GetExcelByte(dt, modelReturn.errMessage);
                    string basestr = Convert.ToBase64String(result);
        返回值为base64的字符串
                    return basestr;
        而前台,在需要多加一步操作,可以直接下载:
        //res.data 为异步返回值,就是basestr
        window.location.href = "data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64," + res.data;


        /// <summary>
        /// datatable导出
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        public byte[] GetExcelByte(DataTable dt, string err)
        {
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet workSheet = package.Workbook.Worksheets.Add("候车亭批量导入");
                workSheet.Cells[1, 1].Value = "媒体类型*";
                workSheet.Cells[1, 2].Value = "类型子类*";
                workSheet.Cells[1, 3].Value = "媒体位置*";
                for (int i = 1; i < dt.Rows.Count; i++)
                {
                    DataRow dr = dt.Rows[i];
                    workSheet.Cells[i + 1, 1].Value = dr[0];
                    workSheet.Cells[i + 1, 2].Value = dr[1];
                    workSheet.Cells[i + 1, 3].Value = dr[2];
                }
                return package.GetAsByteArray();
            }
        }

        /// <summary>
        /// execl转成table
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public DataTable ExcelToTable(string path)
        {
            DataTable vTable = new DataTable();
            FileInfo existingFile = new FileInfo(path);
            try
            {
                FileInfo file = new FileInfo(path);
                using (ExcelPackage package = new ExcelPackage(file))
                {
                    ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
                    int vSheetCount = package.Workbook.Worksheets.Count;
                    //获取总Sheet页
                    int maxColumnNum = worksheet.Dimension.End.Column;//最大列
                    int minColumnNum = worksheet.Dimension.Start.Column;//最小列
                    int maxRowNum = worksheet.Dimension.End.Row;//最小行
                    int minRowNum = worksheet.Dimension.Start.Row;//最大行

                    DataColumn vC;
                    for (int j = 1; j <= maxColumnNum; j++)
                    {
                        vC = new DataColumn("A_" + j, typeof(string));
                        vTable.Columns.Add(vC);
                    }
                    for (int n = 1; n <= maxRowNum; n++)
                    {
                        DataRow vRow = vTable.NewRow();
                        for (int m = 1; m <= maxColumnNum; m++)
                        {
                            vRow[m - 1] = worksheet.Cells[n, m].Value;
                        }
                        vTable.Rows.Add(vRow);
                    }
                }

            }
            catch (Exception vErr)
            {
                Console.WriteLine(vErr.Message);
            }
            return vTable;
        }
        /// <summary>
        /// 把二进制流转成文件
        /// </summary>
        /// <param name="path">二进制流,类似(data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;base64,)开头的字符串</param>
        /// <param name="path">文件扩展名</param>
        /// <returns></returns>
        public string UploadExecl(string path, string extension)
        {
            string sPath = host.ContentRootPath + "\\BatchUpload";//保存的路径
            if (!Directory.Exists(sPath))
            {
                Directory.CreateDirectory(sPath);
            }
            var regex = new Regex(@"data:(?<mime>[\w/\-\.]+);(?<encoding>\w+),(?<data>.*)", RegexOptions.Compiled);
            var match = regex.Match(path);

            var mimeType = match.Groups["mime"].Value;
            var encodingCode = match.Groups["encoding"].Value;
            var data = match.Groups["data"].Value;
            byte[] targetFileByte = Convert.FromBase64String(data);

            string[] mimeExtension = mimeType.Split(‘/‘);
            string fileExtension = extension;
            Random random = new Random();
            //文件保存
            string fileName = string.Format("{0:yyyyMMddHHmmss}{1}", DateTime.Now, random.Next());
            string filePath = string.Format("{0}\\{1}.{2}", sPath, fileName, fileExtension);
            FileStream file = new FileStream(filePath, FileMode.CreateNew, FileAccess.Write);
            file.Write(targetFileByte,0, targetFileByte.Length);
            file.Close();

            return filePath;
        }

ExcelPackage导入导出,命名空间一定要是EPPlus

标签:.com   message   summary   excel   tor   line   catch   cell   com   

原文地址:https://www.cnblogs.com/randy619/p/8119420.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!