简单的excel导入导出示例分享

前端技术 2023/09/02 C#

复制代码 代码如下:

/// <summary>
        /// 导出Excel
        /// </summary>
        /// <param name=\"stime\"></param>
        /// <param name=\"etime\"></param>
        /// <returns></returns>
        public ActionResult Export(FormCollection frm)
        {
            DataTable dts = new DataTable();
            dts = _shopMemeber.ExportMemberData(frm);
            IWorkbook workbook = new XSSFWorkbook();
            ISheet sheet = workbook.CreateSheet();
            IRow headerRow = sheet.CreateRow(0);
            foreach (DataColumn column in dts.Columns)
                headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);
            int rowIndex = 1;
            foreach (DataRow row in dts.Rows)
            {
                IRow dataRow = sheet.CreateRow(rowIndex);
                foreach (DataColumn column in dts.Columns)
                {
                    dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
                }
                rowIndex++;
            }
            string filepath = Server.MapPath(\"/\") + @\"用户列表.xlsx\";
            FileStream file = new FileStream(filepath, FileMode.Create);
            workbook.Write(file);
            ExcelHelper.DownLoad(@\"/用户列表.xlsx\");
            #region 不启用

            #endregion
            return SuccessMsg(\"AdminMemberMemberIndex\");
        }
//这个是下载到桌面的方法,没实现自选路径
public static void DownLoad(string FileName)
 {
             FileInfo fileInfo = new FileInfo(HttpContext.Current.Server.MapPath(FileName));
             //以字符流的形式下载文件
             FileStream fs = new FileStream(HttpContext.Current.Server.MapPath(FileName), 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(fileInfo.Name, System.Text.Encoding.UTF8));
          HttpContext.Current.Response.BinaryWrite(bytes);
           HttpContext.Current.Response.Flush();
            HttpContext.Current.Response.End();
        }

本文地址:https://www.stayed.cn/item/5439

转载请注明出处。

本站部分内容来源于网络,如侵犯到您的权益,请 联系我

我的博客

人生若只如初见,何事秋风悲画扇。