根据excel模版导出数据到excel

添加dll:

调用方式:

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. int num = Convert.ToInt32(this.ddlYear.SelectedValue);  
  2.  int num2 = Convert.ToInt32(this.ddlMonth.SelectedValue);  
  3.   
  4.  string tempPath = "";  
  5. 位置  
  6.  tempPath =HttpContext.Current.Request.PhysicalApplicationPath + @"excel\huizongtemplate.xls";  
  7.   
  8.  if (tempPath.Length > 0)  
  9.  {  
  10. 取数据源  
[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. DataTable dt = new DataTable();  
  2. this.GenerataNewTable(dt);  
  3. this.GetAttributesValue(dt, num, num2);  
  4. if (dt != null && dt.Rows.Count > 0)  
  5. {  
  6.     string bakPath = HttpContext.Current.Request.PhysicalApplicationPath + @"excel\" + DateTime.Now.ToString("yyyyMMddHHmmss") + "huizong.xls";  
  7.    //设置文件名   
[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. string filename = bakPath.Substring(bakPath.LastIndexOf('\\') + 1);  
  2.                  ExcelHelper.ExportExcelForDtByNPOI(dt, filename, tempPath, 1, "");  
  3.   
  4.              }  
  5.              else  
  6.              {  
  7.                  return;  
  8.              }  
  9.          }  


ExcelHelper类:

 

[html]  view plain copy print ? 在CODE上查看代码片 派生到我的代码片
  1. public class ExcelHelper  
  2.    {  
  3.   
  4.        #region XZH 2011.3  
  5.   
  6.        #region HandleExcel  
  7.   
  8.   
  9.        /// <summary>  
  10.        /// 利用模板,DataTable导出到Excel(单个类别)  
  11.        /// </summary>  
  12.        /// <param name="dtSource">DataTable</param>  
  13.        /// <param name="strFileName">生成的文件路径、名称</param>  
  14.        /// <param name="strTemplateFileName">模板的文件路径、名称</param>  
  15.        /// <param name="flg">文件标识(1:经营贸易情况/2:生产经营情况/3:项目投资情况/4:房产销售情况/其他:总表)</param>  
  16.        /// <param name="titleName">表头名称</param>  
  17.        public static void ExportExcelForDtByNPOI(DataTable dtSource, string strFileName, string strTemplateFileName, int flg, string titleName)  
  18.        {  
  19.            // 利用模板,DataTable导出到Excel(单个类别)  
  20.            using (MemoryStream ms = ExportExcelForDtByNPOI(dtSource, strTemplateFileName, flg, titleName))  
  21.            {  
  22.                using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))  
  23.                {  
  24.                byte[] data = ms.ToArray();  
  25.                //fs.Write(data, 0, data.Length);  
  26.   
  27.                #region 客户端保存  
  28.                HttpResponse response = System.Web.HttpContext.Current.Response;  
  29.                response.Clear();  
  30.                //Encoding pageEncode = Encoding.GetEncoding(PageEncode);  
  31.                response.Charset = "UTF-8";  
  32.                response.ContentType = "application/vnd-excel";//"application/vnd.ms-excel";  
  33.                System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + strFileName));  
  34.                System.Web.HttpContext.Current.Response.BinaryWrite(data);  
  35.                #endregion  
  36.   
  37.                    fs.Flush();  
  38.                }  
  39.            }  
  40.        }  
  41.   
  42.   
  43.   
  44.   
  45.   
  46.   
  47.        /// <summary>  
  48.        /// 利用模板,DataTable导出到Excel(单个类别)  
  49.        /// </summary>  
  50.        /// <param name="dtSource">DataTable</param>  
  51.        /// <param name="strTemplateFileName">模板的文件路径、名称</param>  
  52.        /// <param name="flg">文件标识--sheet名(1:经营贸易情况/2:生产经营情况/3:项目投资情况/4:房产销售情况/其他:总表)</param>  
  53.        /// <param name="titleName">表头名称</param>  
  54.        /// <returns></returns>  
  55.        private static MemoryStream ExportExcelForDtByNPOI(DataTable dtSource, string strTemplateFileName, int flg, string titleName)  
  56.        {  
  57.   
  58.            #region 处理DataTable,处理明细表中没有而需要额外读取汇总值的两列  
  59.   
  60.            #endregion  
  61.            int totalIndex = 20;        // 每个类别的总行数  
  62.            int rowIndex = 2;       // 起始行  
  63.            int dtRowIndex = dtSource.Rows.Count;       // DataTable的数据行数  
  64.   
  65.            FileStream file = new FileStream(strTemplateFileName, FileMode.Open, FileAccess.Read);//读入excel模板  
  66.            HSSFWorkbook workbook = new HSSFWorkbook(file);  
  67.            string sheetName = "";  
  68.            switch (flg)  
  69.            {  
  70.                case 1:  
  71.                    sheetName = "各窗口单位服务情况汇总表";  
  72.                    break;  
  73.            }  
  74.            HSSFSheet sheet = workbook.GetSheet(sheetName);  
  75.   
  76.            #region 右击文件 属性信息  
  77.            //{  
  78.            //    DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();  
  79.            //    dsi.Company = "农发集团";  
  80.            //    workbook.DocumentSummaryInformation = dsi;  
  81.   
  82.            //    SummaryInformation si = PropertySetFactory.CreateSummaryInformation();  
  83.            //    si.Author = "农发集团"; //填加xls文件作者信息  
  84.            //    si.ApplicationName = "瞬时达"; //填加xls文件创建程序信息  
  85.            //    si.LastAuthor = "瞬时达"; //填加xls文件最后保存者信息  
  86.            //    si.Comments = "瞬时达"; //填加xls文件作者信息  
  87.            //    si.Title = "农发集团报表"; //填加xls文件标题信息  
  88.            //    si.Subject = "农发集团报表";//填加文件主题信息  
  89.            //    si.CreateDateTime = DateTime.Now;  
  90.            //    workbook.SummaryInformation = si;  
  91.            //}  
  92.            #endregion  
  93.   
  94.            #region 表头  
  95.            HSSFRow headerRow = sheet.GetRow(0);  
  96.            HSSFCell headerCell = headerRow.GetCell(0);  
  97.            headerCell.SetCellValue(titleName);  
  98.            #endregion  
  99.   
  100.            // 隐藏多余行  
  101.            for (int i = rowIndex + dtRowIndex; i < rowIndex + totalIndex; i++)  
  102.            {  
  103.                HSSFRow dataRowD = sheet.GetRow(i);  
  104.                dataRowD.Height = 0;  
  105.                dataRowD.ZeroHeight = true;  
  106.                //sheet.RemoveRow(dataRowD);  
  107.            }  
  108.   
  109.            foreach (DataRow row in dtSource.Rows)  
  110.            {  
  111.                #region 填充内容  
  112.                HSSFRow dataRow = sheet.GetRow(rowIndex);  
  113.   
  114.                int columnIndex = 1;        // 开始列(0为标题列,从1开始)  
  115.                foreach (DataColumn column in dtSource.Columns)  
  116.                {  
  117.                    // 列序号赋值  
  118.                    if (columnIndex >= dtSource.Columns.Count)  
  119.                        break;  
  120.   
  121.                    HSSFCell newCell = dataRow.GetCell(columnIndex);  
  122.                    if (newCell == null)  
  123.                        newCell = dataRow.CreateCell(columnIndex);  
  124.   
  125.                    string drValue = row[column].ToString();  
  126.   
  127.                    switch (column.DataType.ToString())  
  128.                    {  
  129.                        case "System.String"://字符串类型  
  130.                            newCell.SetCellValue(drValue);  
  131.                            break;  
  132.                        case "System.DateTime"://日期类型  
  133.                            DateTime dateV;  
  134.                            DateTime.TryParse(drValue, out dateV);  
  135.                            newCell.SetCellValue(dateV);  
  136.   
  137.                            break;  
  138.                        case "System.Boolean"://布尔型  
  139.                            bool boolV = false;  
  140.                            bool.TryParse(drValue, out boolV);  
  141.                            newCell.SetCellValue(boolV);  
  142.                            break;  
  143.                        case "System.Int16"://整型  
  144.                        case "System.Int32":  
  145.                        case "System.Int64":  
  146.                        case "System.Byte":  
  147.                            int intV = 0;  
  148.                            int.TryParse(drValue, out intV);  
  149.                            newCell.SetCellValue(intV);  
  150.                            break;  
  151.                        case "System.Decimal"://浮点型  
  152.                        case "System.Double":  
  153.                            double doubV = 0;  
  154.                            double.TryParse(drValue, out doubV);  
  155.                            newCell.SetCellValue(doubV);  
  156.                            break;  
  157.                        case "System.DBNull"://空值处理  
  158.                            newCell.SetCellValue("");  
  159.                            break;  
  160.                        default:  
  161.                            newCell.SetCellValue("");  
  162.                            break;  
  163.                    }  
  164.                    columnIndex++;  
  165.                }  
  166.                #endregion  
  167.   
  168.                rowIndex++;  
  169.            }  
  170.   
  171.   
  172.            // 格式化当前sheet,用于数据total计算  
  173.            sheet.ForceFormulaRecalculation = true;  
  174.   
  175.            #region Clear "0"  
  176.            System.Collections.IEnumerator rows = sheet.GetRowEnumerator();  
  177.   
  178.            int cellCount = headerRow.LastCellNum;  
  179.   
  180.            for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)  
  181.            {  
  182.                HSSFRow row = sheet.GetRow(i);  
  183.                if (row != null)  
  184.                {  
  185.                    for (int j = row.FirstCellNum; j < cellCount; j++)  
  186.                    {  
  187.                        HSSFCell c = row.GetCell(j);  
  188.                        if (c != null)  
  189.                        {  
  190.                            switch (c.CellType)  
  191.                            {  
  192.                                case HSSFCellType.NUMERIC:  
  193.                                    if (c.NumericCellValue == 0)  
  194.                                    {  
  195.                                        c.SetCellType(HSSFCellType.STRING);  
  196.                                        c.SetCellValue(string.Empty);  
  197.                                    }  
  198.                                    break;  
  199.                                case HSSFCellType.BLANK:  
  200.   
  201.                                case HSSFCellType.STRING:  
  202.                                    if (c.StringCellValue == "0")  
  203.                                    { c.SetCellValue(string.Empty); }  
  204.                                    break;  
  205.   
  206.                            }  
  207.                        }  
  208.                    }  
  209.   
  210.                }  
  211.   
  212.            }  
  213.            #endregion  
  214.   
  215.            using (MemoryStream ms = new MemoryStream())  
  216.            {  
  217.                workbook.Write(ms);  
  218.                ms.Flush();  
  219.                ms.Position = 0;  
  220.                sheet = null;  
  221.                workbook = null;  
  222.   
  223.   
  224.                //sheet.Dispose();  
  225.                //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet  
  226.                return ms;  
  227.            }  
  228.        }  
  229.   
  230.        #endregion  
  231.   
  232.   
  233.        #endregion  
  234.    }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值