ext.net 2.5 导出excel的使用方法
前台页面的导入,导出
<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>
/// 发送到client
/// </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(); }
}
}
大概就这么多了。希望对大家实用
ext.net 2.5 导出excel的使用方法的更多相关文章
- 从SQL Server中导入/导出Excel的基本方法(转)
从sql server中导入/导出 excel 的基本方法 /*=========== 导入/导出 excel 的基本方法 ===========*/ 从excel文档中,导入数据到sql数据库中,很 ...
- ASP.net中导出Excel的简单方法介绍
下面介绍一种ASP.net中导出Excel的简单方法 先上代码:前台代码如下(这是自己项目里面写的一点代码先贴出来吧) <div id="export" runat=&quo ...
- MVC 导出Excel 的其中一方法(View导出excel)
场景:mvc下导出excel 思路:使用View导出excel 步骤: 1.导出标签添加事件 $("#export_A").click(function(){ //省略代码.... ...
- <转>.php导出excel(多种方法)
基本上导出的文件分为两种:1:类Excel格式,这个其实不是传统意义上的Excel文件,只是因为Excel的兼容能力强,能够正确打开而已.修改这种文件后再保存,通常会提示你是否要转换成Excel文件. ...
- asp.net中导出excel数据的方法汇总
1.由dataset生成 代码如下 复制代码 public void CreateExcel(DataSet ds,string typeid,string FileName) { Htt ...
- 导出excel的简单方法
excel的操作,最常用的就是导出和导入,废话不多说上代码. 本例使用NPOI实现的,不喜勿喷哈.... /// <summary> /// 导出Excel /// </summar ...
- C# 导出 Excel 的各种方法总结
第一种:使用 Microsoft.Office.Interop.Excel.dll 首先需要安装 office 的 excel,然后再找到 Microsoft.Office.Interop.Excel ...
- 写一个通用的List集合导出excel的通用方法
前几天要做一个数据导出Excel 我就打算写一个通用的. 这样一来用的时候也方便,数据主要是通过Orm取的List.这样写一个通用的刚好. public static void ListToExcel ...
- asp.net导出EXCEL的好方法!(好用,导出全部数据)
1.调用方法: ExportExcel("application/ms-excel", "EXCEL名称.xls", GridView1, this.Page) ...
随机推荐
- Opencascade 选择器算法
算法的阶段 该算法包括预处理和三个主要阶段. 使用深度优先搜索逐层遍历所有对象 . 预处理 计算平截头体及其主要特征的计算. 第一阶段 - 遍历第一级BVH树 在成功构建选择平截头体之后,算法开始遍历 ...
- mybatis-4 mybatis与spring结合使用及原理
1.创建项目maven,方便依赖下载.使用的jar如下: <dependencies> <dependency> <groupId>org.springframew ...
- django authentication
django authentication django session expiry login and logout view.py from django.contrib.auth import ...
- kubeadm1.14.1 安装Metrics Server
Metrics API 介绍Metrics-Server之前,必须要提一下Metrics API的概念 Metrics API相比于之前的监控采集方式(hepaster)是一种新的思路,官方希望核心指 ...
- LInux设备驱动分析—— kmalloc和kzalloc函数
今晚在研究EVM5728开发板上面Linux系统的IIC设备驱动程序,偶然之间看到驱动程序中有一处使用了kzalloc函数,本人之前都是使用Linux内核提供的kmalloc / kfree函数来给设 ...
- css选择器(1)——元素选择器、类名和id选择器
css的主要优点之一就是它能很容易地向所有同类型的元素应用一组样式.当然它是通过选择器来实现这一点的. 基本规则结构: 语法= 选择器 +声明块 1.元素选择器——直接使用html元素名,指向文档元素 ...
- AGC 033
目录 A. Darker and Darker B. LRUD Game 题面 题解 代码 C. Removing Coins 题面 题解 代码 D. Complexity 题面 题解 代码 E. G ...
- Using TCP keepalive under Linux
Linux has built-in support for keepalive. You need to enable TCP/IP networking in order to use it. Y ...
- js中的constructor 和prototype
参考 http://www.cnblogs.com/yupeng/archive/2012/04/06/2435386.html function a(c){ this.b = c; this.d = ...
- STM32F407 STLINK 在线调试 个人笔记
配置的部分请看本博客STM32分类下的环境配置篇目 开始调试 一些按键 查看寄存器 查看变量值 选中变量,右键,add to watch