博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C# Excel导入导出
阅读量:6598 次
发布时间:2019-06-24

本文共 4575 字,大约阅读时间需要 15 分钟。

 

 

///         /// 导出Excel        ///         /// 
/// 数据源List
///
页面文件 输出名称 *.xls public void Export
(IList
list, string fileName) { //得到DataTable System.Data.DataTable dt = ListToTableHelper.ToDataTable(list); //导出Excel的临时文件 string exportPath = Server.MapPath("~/Excel/") + DateTime.Now.Ticks + fileName; CreateExcel(dt, exportPath); FileInfo fileInfo = new FileInfo(exportPath); if (fileInfo.Exists) { const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力 byte[] buffer = new byte[ChunkSize]; Response.Clear(); System.IO.FileStream iStream = System.IO.File.OpenRead(exportPath); long dataLengthToRead = iStream.Length;//获取下载的文件总大小 Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName)); while (dataLengthToRead > 0 && Response.IsClientConnected) { int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小 Response.OutputStream.Write(buffer, 0, lengthRead); Response.Flush(); dataLengthToRead = dataLengthToRead - lengthRead; } iStream.Close(); Response.Close(); } // 删除生成的Excel 临时文件 File.Delete(exportPath); }

 

 

 

///         /// 打开模板Excel,重新写入 另存Excel 文件格式 xls 97-2003        ///         ///         ///         ///         public void CreateExcel(System.Data.DataTable dt, string savePath)        {            savePath = savePath.Replace("/", "\\");            Application application = new ApplicationClass();            application.Visible = false;            //创建 新的Excel            Workbook workbook = application.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);            //插入 现有的Excel            //application.Workbooks._Open(tempExcelPath, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);            Worksheet worksheet = (Worksheet)workbook.Sheets[1];            int rowNum = 1;            int excelColumNum = 0;            try            {                int count = dt.Rows.Count;                for (int i = 0; i < dt.Columns.Count; i++)                {                    worksheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;                    Range range = (Microsoft.Office.Interop.Excel.Range)worksheet.Cells[1, i + 1];                    range.Interior.ColorIndex = 15;                    range.Font.Bold = true;                }                foreach (System.Data.DataRow row in dt.Rows)                {                    rowNum++;                    //Console.WriteLine("当前处理记录:{0}/{1}", rowNum, count);                    for (int i = 1; i <= dt.Columns.Count; i++)                    {                        excelColumNum = i;                        string text = row[i - 1].ToString();                        Range range = (Range)worksheet.Cells[rowNum, excelColumNum];                        range.Value2 = text;                    }                }                workbook.Saved = true;                workbook.SaveAs(savePath, XlFileFormat.xlExcel8, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);                workbook.Close(true, Type.Missing, Type.Missing);                workbook = null;                application.Quit();                GC.Collect();            }            catch            {                workbook.Saved = false;                workbook.Close(true, Type.Missing, Type.Missing);                workbook = null;                application.Quit();                GC.Collect();            }        }

 

调用:

protected void btn_ExportExcel_Click(object sender, EventArgs e)        {                        IList
list = new List
();// 数据源 string fileName = "data.xls"; //页面文件 输出名称 Export(list, fileName); //调用方法 ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('成功!')", true); //完成后显示消息 }

  

 

 

 

转载于:https://www.cnblogs.com/mjxxsc/p/3573059.html

你可能感兴趣的文章
通过 LLVM 在 Android 上运行 Swift 代码
查看>>
《C程序员从校园到职场》一第2章 学校到职场2.1 认清自身不足
查看>>
jquery遍历的json有两层list时的解决方法
查看>>
Sql语句-case when then else end
查看>>
Python_编程特色
查看>>
ant打jar包
查看>>
【Android】The application has stopped unexpectedly.Please try again.
查看>>
为什么要使用Ajax
查看>>
java web开发使用伪静态
查看>>
CISCO交换机密码恢复
查看>>
我的友情链接
查看>>
有关在linux 下跑asp.net文章博客
查看>>
Linux/Unix的精巧约定两例及其简析:目录权限和文本行数
查看>>
WebDAV助手1.1.0更新
查看>>
[CTSC2018]青蕈领主
查看>>
原型继承
查看>>
找不到ifconfig命令
查看>>
微服务事务处理
查看>>
用Groovy进行单元测试
查看>>
github地址
查看>>