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

Posted 小王大王

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ExcelPackage导入导出,命名空间一定要是EPPlus相关的知识,希望对你有一定的参考价值。

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的主要内容,如果未能解决你的问题,请参考以下文章

使用ExcelPackage进行Excel报表

如何从命名空间导出,访问默认值? [复制]

EPPlus--ExcelPackage 导出Excel

我想把WinForm上的内容导出为PDF文档,用C# VS2010 需要引用哪些 dll ,导入哪些命名空间?具体怎么做呢?

sql数据导入导出问题

面相对象之命名空间注意事项