前台页面的导入,导出
<ext:FileUploadField ID="FileUploadField_Import" runat="server" ButtonOnly="true" ButtonText="导入" Icon="PackageIn"> <DirectEvents> <Change OnEvent="ImportExcelClick"> <EventMask ShowMask="true" Msg="正在导入数据,请稍后... ..."></EventMask> </Change> </DirectEvents> </ext:FileUploadField> <ext:Button ID="Button_ExportExcel" runat="server" Text="导出" Icon="PackageGo"> <DirectEvents> <Click OnEvent="ExportExcel_Click" IsUpload="true" > <ExtraParams > <ext:Parameter Name="GridLargeTypePanelData" Value="System.GridPanel_Data.getRowsValues({selectedOnly : false,visibleOnly:true})" Mode="Raw"/> </ExtraParams> </Click> </DirectEvents> </ext:Button>
后台的导入导出
/// <summary> /// 导入 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void ImportExcelClick(object sender, DirectEventArgs e) { if (this.FileUploadField_Import.PostedFile.InputStream.Length == 0) return; //导入配置 ExcelTemplate excel = new ExcelTemplate(1, this.FileUploadField_Import.PostedFile.InputStream); using (DataTable dt = excel.ExportToDataTable()) { Hashtable info; CResult result = null; DataRow[] rows = dt.Select("CODE LIKE '%00-000'", "CODE"); if (rows.Length > 0) { //你自己的代码 } } this.FileUploadField_Import.Reset(); }
/// <summary> /// 导出Excel /// </summary> /// <param name="sender"></param> /// <param name="e"></param> public void ExportExcel_Click(object sender, DirectEventArgs e) { string json = e.ExtraParams["GridLargeTypePanelData"].ToString(); foreach (ColumnBase item in this.GridPanel_Data.ColumnModel.Columns) { if (!item.Hidden) { json = json.Replace("\"" + item.DataIndex + "\":", "\"" + item.Text + "\":"); } } this.ToExcel(json); //父类的方法 }
导出的父类方法
/// <summary> /// 导出Excel /// </summary> /// <param name="json"></param> public void ToExcel(string json) { StoreSubmitDataEventArgs eSubmit = new StoreSubmitDataEventArgs(json, null); XmlNode xml = eSubmit.Xml; this.Response.Clear(); this.Response.ContentType = "application/vnd.ms-excel"; this.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode("导出信息" + DateTime.Now.ToString("yyyyMMddhhmmss") + ".xls", Encoding.UTF8).ToString()); XslCompiledTransform xtExcel = new XslCompiledTransform(); xtExcel.Load(HttpContext.Current.Request.PhysicalApplicationPath + string.Format(@"Templates/通用导出.xslt")); xtExcel.Transform(xml, null, this.Response.OutputStream); this.Response.End(); }
通用导出的文件.xslt
<?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:user="urn:my-scripts" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"> <xsl:template match="/"> <Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet" xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet" xmlns:html="http://www.w3.org/TR/REC-html40"> <xsl:apply-templates/> </Workbook> </xsl:template> <xsl:template match="/*"> <Worksheet> <xsl:attribute name="ss:Name"> <xsl:value-of select="local-name(/*/*)" /> </xsl:attribute> <Table x:FullColumns="1" x:FullRows="1"> <Row> <xsl:for-each select="*[position() = 1]/*"> <Cell> <Data ss:Type="String"> <xsl:value-of select="local-name()" /> </Data> </Cell> </xsl:for-each> </Row> <xsl:apply-templates/> </Table> </Worksheet> </xsl:template> <xsl:template match="/*/*"> <Row> <xsl:apply-templates/> </Row> </xsl:template> <xsl:template match="/*/*/*"> <Cell> <Data ss:Type="String"> <xsl:value-of select="." /> </Data> </Cell> </xsl:template> </xsl:stylesheet>
导入代码下来就是封装的类文件 ,源码
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Collections; namespace EQU.UI.Base { public class ExcelSetting : ArrayList { /// <summary> /// excel配置对象 /// </summary> public ExcelSetting() : base() { } /// <summary> /// 以键值对的形式添加HeaderInfo结构 /// </summary> /// <param name="p_FiledName"></param> /// <param name="p_DisplayName"></param> /// <returns></returns> public int Add(string p_FiledName, string p_DisplayName) { HeaderInfo info = new HeaderInfo(); info.DisplayName = p_DisplayName; info.FiledName = p_FiledName; return this.Add(info); } /// <summary> /// 批量添加可显示的结构单元 /// </summary> /// <param name="p_Fileds"></param> /// <param name="p_Displaies"></param> /// <returns></returns> public int AddRange(string[] p_Fileds, string[] p_Displaies) { if (p_Fileds.Length != p_Displaies.Length) return -1; for (int i = 0; i < p_Fileds.Length; i++) { this.Add(p_Fileds[i], p_Displaies[i]); } return this.Count; } /// <summary> /// 批量添加可显示的结构单元 /// </summary> /// <param name="p_Fileds"></param> /// <param name="p_Displaies"></param> /// <returns></returns> public int AddRange(ArrayList p_Fileds, ArrayList p_Displaies) { if (p_Fileds.Count != p_Displaies.Count) return -1; for (int i = 0; i < p_Fileds.Count - 1; i++) { this.Add(p_Fileds[i].ToString(), p_Displaies[i].ToString()); } return this.Count; } } /// <summary> /// Excel头信息结构体 /// </summary> public struct HeaderInfo { /// <summary> /// 用来显示字段的原始名称 /// </summary> public string FiledName; /// <summary> /// 显示字段显示名称 /// </summary> public string DisplayName; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using NPOI.SS.UserModel; using System.IO; using System.Data; using NPOI.HPSF; using NPOI.HSSF.UserModel; using System.Text; namespace EQU.UI.Base { public class ExcelTemplate { /// <summary> /// 模板起始页标记 /// </summary> public int ItemIndex = 3; IWorkbook hssfworkbook; //HSSFWorkbook hssfworkbook; 2015-2-5刘超 替换Npoi版本 private ExcelSetting m_ExcelSetting = null; /// <summary> /// 获取或设置结构设置 /// </summary> public ExcelSetting ExcelSetting { get { return this.m_ExcelSetting; } set { this.m_ExcelSetting = value; } } public ExcelTemplate() { } /// <summary> /// 现有的配置构造导出实例 /// </summary> /// <param name="p_Setting"></param> public ExcelTemplate(string p_TempPath) { using (FileStream file = new FileStream(HttpContext.Current.Request.PhysicalApplicationPath + string.Format(@"Templates/other/{0}", p_TempPath), FileMode.Open, FileAccess.Read)) { //将文件流中模板加载到工作簿对象中 hssfworkbook = WorkbookFactory.Create(file); } } /// <summary> /// 现有的配置构造导出实例 /// </summary> /// <param name="p_Setting"></param> public ExcelTemplate(int p_tempRow, string p_TempPath) { this.ItemIndex = p_tempRow; using (FileStream file = new FileStream(HttpContext.Current.Request.PhysicalApplicationPath + string.Format(@"Templates/other/{0}", p_TempPath), FileMode.Open, FileAccess.Read)) { //将文件流中模板加载到工作簿对象中 hssfworkbook = WorkbookFactory.Create(file); } } /// <summary> /// 打开一个 Excel 的某个Sheet /// </summary> /// <param name="p_tempRow">字段行</param> /// <param name="p_Stream">流</param> public ExcelTemplate(int p_tempRow, Stream p_Stream) { this.ItemIndex = p_tempRow; hssfworkbook = WorkbookFactory.Create(p_Stream); } /// <summary> /// 展现到Excel文件 /// </summary> /// <param name="dtSource">数据源</param> /// <param name="strHeaderText">显示表头的标题</param> /// <param name="useEmptyTitle">是否显示数据集中的空标题,若为true,则显示字段的名称</param> /// <returns></returns> public MemoryStream RenderToExcel(DataTable dtSource, string strHeaderText) { IWorkbook workbook = hssfworkbook; ISheet sheet = workbook.GetSheet("Sheet1"); #region 右击文件 属性信息 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "NPOI"; (workbook as HSSFWorkbook).DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = "文件作者信息"; //填加xls文件作者信息 si.ApplicationName = "创建程序信息"; //填加xls文件创建程序信息 si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息 si.Comments = "作者信息"; //填加xls文件作者信息 si.Title = "标题信息"; //填加xls文件标题信息 si.Subject = "主题信息";//填加文件主题信息 si.CreateDateTime = DateTime.Now; (workbook as HSSFWorkbook).SummaryInformation = si; } #endregion //获取模板样式 IRow tempRow = sheet.GetRow(this.ItemIndex);//模板行 tempRow.ZeroHeight = true;//隐藏模板 ICellStyle dateStyle = workbook.CreateCellStyle(); //dateStyle.BorderBottom = BorderStyle.THIN; //dateStyle.BorderLeft = BorderStyle.THIN; //dateStyle.BorderRight = BorderStyle.THIN; //dateStyle.BorderTop = BorderStyle.THIN; IDataFormat format = workbook.CreateDataFormat(); int rowIndex = ItemIndex + 1; foreach (DataRow row in dtSource.Rows) { #region 填充内容 IRow dataRow = sheet.CreateRow(rowIndex); //foreach (DataColumn column in dtSource.Columns) foreach (ICell item in tempRow.Cells) { ICell newCell = dataRow.CreateCell(item.ColumnIndex); dateStyle = item.CellStyle; newCell.CellStyle = dateStyle; if (string.IsNullOrEmpty(item.ToString())) { continue; } DataColumn column = dtSource.Columns[item.ToString().Trim()]; string drValue = row[column].ToString(); switch (column.DataType.ToString()) { case "System.String"://字符串类型 if (drValue == "0") newCell.SetCellValue(string.Empty); else newCell.SetCellValue(drValue); //newCell.SetCellValue(drValue); break; case "System.DateTime"://日期类型 if (string.IsNullOrEmpty(drValue)) { item.SetCellValue(string.Empty); break; }; DateTime dateV; bool istr = DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); break; case "System.Boolean"://布尔型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); if (intV == 0) newCell.SetCellValue(string.Empty); else newCell.SetCellValue(intV); break; case "System.Decimal"://浮点型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); //newCell.SetCellValue(doubV); if (doubV == 0) newCell.SetCellValue(string.Empty); else newCell.SetCellValue(doubV); break; case "System.DBNull"://空值处理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } #endregion rowIndex++; } //sheet.ShiftRows(this.ItemIndex+1, sheet.LastRowNum, -1); using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; //sheet.Dispose(); //workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet return ms; } } /// <summary> /// 把Sheet中的数据转换为DataTable /// </summary> /// <param name="sheet"></param> /// <returns></returns> public DataTable ExportToDataTable() { DataTable dt = new DataTable(); IWorkbook workbook = hssfworkbook; ISheet sheet = workbook.GetSheet("Sheet1"); //默认,第一行是字段 IRow headRow = sheet.GetRow(this.ItemIndex); //设置datatable字段 for (int i = headRow.FirstCellNum, len = headRow.LastCellNum; i < len; i++) { dt.Columns.Add(headRow.Cells[i].StringCellValue); } //遍历数据行 for (int i = (this.ItemIndex + 1), len = sheet.LastRowNum + 1; i < len; i++) { IRow tempRow = sheet.GetRow(i); DataRow dataRow = dt.NewRow(); //遍历一行的每一个单元格 for (int r = 0, j = tempRow.FirstCellNum, len2 = tempRow.LastCellNum; j < len2; j++, r++) { ICell cell = tempRow.GetCell(j); if (cell != null) { switch (cell.CellType) { case CellType.String: dataRow[r] = cell.StringCellValue; break; case CellType.Numeric: DateTime dtDate; if (DateTime.TryParse(cell.ToString(), out dtDate)) { dataRow[r] = dtDate; } else { dataRow[r] = cell.NumericCellValue; } break; case CellType.Boolean: dataRow[r] = cell.BooleanCellValue; break; default: dataRow[r] = ""; break; } } } dt.Rows.Add(dataRow); } return dt; } //保存到文件 public void SaveToFile(MemoryStream ms, string fileName) { using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write)) { byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length); fs.Flush(); data = null; } } /// <summary> /// 发送到客户端 /// </summary> /// <param name="ms"></param> /// <param name="context"></param> /// <param name="fileName"></param> public void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName) { if (context.Request.Browser.Browser == "IE") fileName = HttpUtility.UrlEncode(fileName); context.Response.ContentType = "application/x-zip-compressed"; context.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, Encoding.UTF8).ToString()); context.Response.BinaryWrite(ms.GetBuffer()); context.Response.End(); } } }
大概就这么多了,希望对大家有用
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-05 21:52:17