zoukankan      html  css  js  c++  java
  • 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;
            }

  • 相关阅读:
    P3162 [CQOI2012]组装
    P3161 [CQOI2012]模拟工厂
    P3158 [CQOI2011]放棋子
    P3154 [CQOI2009]循环赛
    zabbix部署监控端(server)以及页面优化
    zabbix-agent端自定义监控项(free -m)服务器内存使用率
    java应用系统运行速度慢的解决方法
    at org.apache.hadoop.hbase.tmpl.master.BackupMasterStatusTmplImpl.renderNoFlush(BackupMasterStatusTm
    解决Hbase启动后,hmaster会在几秒钟后自动关闭(停掉)!!!
    全网最详细的Hadoop HA集群启动后,两个namenode都是standby的解决办法(图文详解)
  • 原文地址:https://www.cnblogs.com/randy619/p/8119420.html
Copyright © 2011-2022 走看看