zoukankan      html  css  js  c++  java
  • C#使用NPOI导出Excel表格

    using NPOI.HSSF.UserModel;
    using NPOI.SS.UserModel;

     

    /// <summary> /// DataTable导出Excel /// </summary> /// <param name="dt">datatable数据源</param> /// <param name="strFileName">文件名</param> /// <param name="strSheetName">工作簿名</param> public void ExportExcel(DataTable dt, string strFileName, string strSheetName) { HSSFWorkbook book = new HSSFWorkbook(); ISheet sheet = book.CreateSheet(strSheetName); IRow headerrow = sheet.CreateRow(0); ICellStyle style = book.CreateCellStyle(); style.Alignment = HorizontalAlignment.Center; style.VerticalAlignment = VerticalAlignment.Center; HSSFRow dataRow = (HSSFRow)sheet.CreateRow(0); string strColumns = "治具编号,验收项目,数据,连片类型,Gerber,光板料号,适用机种,制作厂家,厂商确认,进厂日期,应力测试日期"; string[] strArry = strColumns.Split(','); for (int i = 0; i < strArry.Length; i++) { dataRow.CreateCell(i).SetCellValue(strArry[i]); dataRow.GetCell(i).CellStyle = style; } for (int i = 0; i < dt.Rows.Count; i++) { dataRow = (HSSFRow)sheet.CreateRow(i + 1); for (int j = 0; j < dt.Columns.Count; j++) { string ValueType = ""; string Value = ""; if (dt.Rows[i][j].ToString() != null) { ValueType = dt.Rows[i][j].GetType().ToString(); Value = dt.Rows[i][j].ToString(); } switch (ValueType) { case "System.String"://字符串类型 dataRow.CreateCell(j).SetCellValue(Value); break; case "System.DateTime"://日期类型 System.DateTime dateV; System.DateTime.TryParse(Value, out dateV); dataRow.CreateCell(j).SetCellValue(dateV); break; case "System.Boolean"://布尔型 bool boolV = false; bool.TryParse(Value, out boolV); dataRow.CreateCell(j).SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(Value, out intV); dataRow.CreateCell(j).SetCellValue(intV); break; case "System.Decimal"://浮点型 case "System.Double": double doubV = 0; double.TryParse(Value, out doubV); dataRow.CreateCell(j).SetCellValue(doubV); break; case "System.DBNull"://空值处理 dataRow.CreateCell(j).SetCellValue(""); break; default: dataRow.CreateCell(j).SetCellValue(""); break; } dataRow.GetCell(j).CellStyle = style; //设置宽度 sheet.SetColumnWidth(j, (Value.Length + 10) * 256); } } MemoryStream ms = new MemoryStream(); book.Write(ms); Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", HttpUtility.UrlEncode(strFileName, System.Text.Encoding.UTF8))); Response.BinaryWrite(ms.ToArray()); Response.End(); book = null; ms.Close(); ms.Dispose(); }
  • 相关阅读:
    数据持久化的复习
    iOS: 消息通信中的Notification&KVO
    iOS 证书与签名 解惑详解
    数据持久化 技术比较
    iOS开发拓展篇-XMPP简单介绍
    iOS block并发
    Xcode把应用程序打包成ipa
    谈谈用SQLite和FMDB而不用Core Data
    cannot use the same dataset for report.dataset and page.dataset
    cxGRID中的字段怎么能以0.00的格式显示
  • 原文地址:https://www.cnblogs.com/vichin/p/5995335.html
Copyright © 2011-2022 走看看