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) ...
随机推荐
- Hibernate-02 HQL实用技术
学习任务 Query接口的使用 HQL基本用法 动态参数绑定查询 HQL的使用 Hibernate支持三种查询方式:HQL查询.Criateria查询.Native SQL查询. HQL是Hibern ...
- HDU4300 Clairewd’s message(拓展kmp)
Problem Description Clairewd is a member of FBI. After several years concealing in BUPT, she interce ...
- PyTorch的十七个损失函数
本文截取自<PyTorch 模型训练实用教程>,获取全文pdf请点击: tensor-yu/PyTorch_Tutorialgithub.com 版权声明:本文为博主原创文章,转载请附上 ...
- POJ - 3126 - Prime Path(BFS)
Prime Path POJ - 3126 题意: 给出两个四位素数 a , b.然后从a开始,每次可以改变四位中的一位数字,变成 c,c 可以接着变,直到变成b为止.要求 c 必须是素数.求变换次数 ...
- PHP将数据库的数据转换成json格式
header('content-type:application/json;charset=utf8'); $results = array(); while ($row = mysql_f ...
- 常见的User-Agent
User_Agent = ["Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3_2 like Mac OS X; zh-cn) AppleWebKit/533. ...
- 如何用纯 CSS 创作一个冒着热气的咖啡杯
效果预览 在线演示 按下右侧的"点击预览"按钮在当前页面预览,点击链接全屏预览. https://codepen.io/zhang-ou/pen/xjXxoz 可交互视频教程 此视 ...
- 虚拟机如何设置静态IP
一.本机环境 Mac.VMware Fusion 10, CentOS6.8 二.设置静态IP地址 1.选择网络连接模式,选择NAT模式 注意: 1)必须要选择NAT模式,否则你的虚拟机与主机始终会在 ...
- 发布tomcate时报A configuration error occurred during startup.please verify the preference field with the prompat:null
发布tomcate时报A configuration error occurred during startup.please verify the preference field with the ...
- C#中的ComboBox实现只能选择不能输入,且下拉框中有默认值。
下拉框有DropDownStyle这一属性,把DropDownStyle类型选为DropDownList,则下拉框只能选择不能输入了.但是这时的下拉框是没有默认值的,即使在Text属性中输入默认值,也 ...