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>
        /// 发送到客户端
        /// </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

ext.net 2.5 导出excel的用法的相关文章

Ext.Net导出Excel

最近项目结束了,其中用到了Ext.Net的GridPanel导出Excel,简单的过程如下: 导出按钮的事件: 1 protected void btnExport_DirectClick(object sender, DirectEventArgs e) 2 { 3 if (Session["BorrowRecord"] != null) 4 { 5 DataTable tbBorrowRecord = (DataTable)Session["BorrowRecord&qu

ext导出excel

poi导出excel http://blog.csdn.net/gavinloo/article/details/6707828 ext自带导出excel http://www.cnblogs.com/kunpengit/archive/2012/07/26/2610236.html

PHP从数据库导出EXCEL文件

参考博客链接:http://www.cnblogs.com/huangcong/p/3687665.html 我的程序代码 原生导出Excel文件 <?phpheader('Content-type: text/html; charset=utf-8');header("Content-type:application/vnd.ms-excel");header("Content-Disposition:filename=test.xls"); $conn =

Struts2+ExtJS+poi导出excel

首先生成Excel import java.io.IOException; import java.io.OutputStream; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.

使用struts2和poi导出excel文档

poi眼下应该是比較流行的操作excel的工具了.这几天做了个struts2和poi结合使用来实现导出excel的功能.个人认为还是比較有用的.代码阅读起来也非常easy.下来就来分享下我的心得 1  struts2的下载excel文件机制 struts2的action中使用poi和输入输出流把二进制数据通过流的形式响应给client.client浏览器作出响应的处理,如弹出文件下载对话框 2  poi的用法 poi解析或生成excel网上资料特别多,这里我就不给出代码了 3 struts文件的

导出Excel之Epplus使用教程2(样式设置)

导出Excel之Epplus使用教程1(基本介绍) 导出Excel之Epplus使用教程2(样式设置) 导出Excel之Epplus使用教程3(图表设置) 导出Excel之Epplus使用教程4(其他设置) 1.公式计算 excel中离不开各种各样的公式计算,在Epplus中运用公式有两种方式,你都可以尝试一下: worksheet.Cells["D2:D5"].Formula = "B2*C2";//这是乘法的公式,意思是第二列乘以第三列的值赋值给第四列,这种方法

Oracle导出excel

oracle导出excel(非csv)的方法有两种,1.使用sqlplus  spool,2.使用包体 现将网上相关代码整理后贴出以备不时之需: 使用sqlplus: 使用sqlplus需要两个文件:sql脚本文件和格式设置文件. 去除冗余信息,main.sql --main.sql 注意,需要在sqlplus下运行 非plsql命令行下 set linesize 200 set term off verify off feedback off pagesize 999 set markup h

thinkphp导入导出excel表单数据

在PHP项目经常要导入导出Excel表单. 先去下载PHPExcel类库文件,放到相应位置. 我在thinkphp框架中的位置为ThinkPHP/Library/Org/Util/ 导入 在页面上传excel文件提交到后台,利用form表单提单即可 <form method="post" enctype="multipart/form-data" action="" > <input type="submit"

C#变成数据导入Excel和导出Excel

excel 基础 •整个excel 表格叫工作表:workbook:工作表包含的叫页:sheet:行:row:单元格:cell. •excel 中的电话号码问题,看起来像数字的字符串以半角单引号开头就没问题了. •使用区域(usedrange):用excel 表的时候不一定是从最左上角的单元格开始用,为了减小文件尺寸,有使用区域的概念,excel 只存储使用区域. 程序处理excel 的技术 •ole automation:程序启动一个excel 进程,然后和excel 进程进行通讯来进行exc