c# Excel导出

Reports.aspx   :

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>资料文库管理</title>
    <script src="../Scripts/boot.js" type="text/javascript"></script>
    <script src="../Scripts/Utility.js" type="text/javascript"></script>
    <script src="../Scripts/anychart_files/js/anychart.js" type="text/javascript"></script>
    <link href="../css/main.css" rel="stylesheet" type="text/css" />
    <style type="text/css">
        body
        {
            margin: 0;
            padding: 0;
            border: 0;
            width: 100%;
            height: 1200px;
            overflow: visible;
        }
    </style>
</head>
<body>
    <div class="mini-panel" style="width: 100%;" showheader="false" showtoolbar="false"
        showclosebutton="false" showfooter="false">
        <div class="contentLeft1" style="min-height: 1150px; width: 170px; margin-left: 0px;">
            <div class="contentLeftTitle" style="width: 170px;">
                <div class="contentLeftTitleIcon">
                </div>
                <div>
                    资料文库</div>
            </div>
            <ul id="ReportType" class="mini-tree" url="ReportManage.ashx?method=LoadTree&selType=<%=selType %>"
                style="padding: 5px; height: 1100px;" showtreeicon="false" textfield="text" idfield="id"
                parentfield="pid" resultastree="false" checkrecursive="true" expand
                scroll="false" allowselect="true" enablehottrack="false" onnodeselect="onnodeselect">
            </ul>
            <div class="clearboth">
            </div>
        </div>
        <div class="contentRight" style="min-height: 1150px; width: 790px;">
            <div class="contentRightTitle" style="width: 790px;">
                <div class="contentRightTableIcon">
                </div>
                <div>
                    资料文库管理</div>
            </div>
            <div class="contentRightButtons">
                <input type="button" id="Export" onclick="Export()" value="导出" />
            </div>
            <div style="margin-top: 2px; width: 790px;">
                <div id="datagrid1" class="mini-datagrid" style="width: 100%; height: 100%; min-height: 1080px;"
                    allowcellwrap="true" idfield="id" allowresize="true" allowresize="true" showpager="true"
                    multiselect="true" pagesize="50" allowalternating="true" pageindexfield="Index"
                    pagesizefield="Size" url="ReportManage.ashx?method=ReportDataMan&menutype=<%=num %>">
                    <div property="columns">
                        <div field="ID" name="ID" width="100" align="center" headeralign="center">
                            ID
                        </div>
                        <div field="Number" width="40" align="center" headeralign="center">
                            序号
                        </div>
                        <div field="XXBT" width="200" align="center" headeralign="center" renderer="onDownReport">
                            标题
                        </div>
                        <div field="TypeNAME" width="60" align="center" headeralign="center">
                            类别
                        </div>
                        <div field="XXSJ" width="90" align="center" headeralign="center">
                            完成时间
                        </div>
                        <div field="USERID" width="60" align="center" headeralign="center" renderer="onReportUSER">
                            录入人
                        </div>
                    </div>
                </div>
            </div>
            <div>
                &nbsp;</div>
            <iframe id="exportIFrame" style="display: none;"></iframe>
        </div>
    </div>
</body>
</html>

<script type="text/javascript">

var num = 0;
    mini.parse();
    var selType = "<%=selType %>";
    var menutype = "<%=num %>";

function Export() {

var grid = mini.get("datagrid1");

var Size = grid.pager.pageSize;

var Index = grid.pager.pageIndex;

var menutype = "<%=num %>";

var url = "ReportManage.ashx?method=Export&pageSize=" + Size + "&pageIndex=" + Index + "&menutype=" + menutype;

var exportIFrame = document.getElementById("exportIFrame");         exportIFrame.src = url;     }

</style>

Reports.aspx.cs  :

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using CNPC.PlatForm.BLL;

using System.Web.Services; using System.Data;

namespace CNPC.PlatForm.Web.Reports {

public partial class Reports : System.Web.UI.Page

{

public int num = 0;

public string selType, NeiID, WaiID = "";

protected void Page_Load(object sender, EventArgs e)

{

ReportBLL datashowBll = new ReportBLL();

selType = Request["selType"];

if (selType == "35") { num = 1; }

}

}

}

ReportManage.ashx   :

using System;

using System.Data;

using System.Drawing;

using System.Reflection;

using System.Runtime.InteropServices;

using System.Text;

using System.Web;

using System.Collections;

using CNPC.PlatForm.BLL;

using System.IO;

using CNPC.PlatForm.Entity;

using System.Collections.Generic;

using CNPC.PlatForm.Dal;

using Microsoft.Office.Interop.Excel;

using DataTable = System.Data.DataTable;

using CNPC.Common.BaseHelper;

namespace CNPC.PlatForm.Web.Reports {

/// <summary>

/// ReportManage1 的摘要说明

/// </summary>

public class ReportManage1 : DataProcess     {

protected override object processQuery(HttpContext context, out bool hasError)

{

string method = context.Request["method"];

hasError = false;

switch (method)             {

//导出全部字段

case "Export":

return Export(context);

default:

return null;

}

}

#region 导出

public string Export(HttpContext context)         {

StringBuilder sBuilder = new StringBuilder();

sBuilder.Append("<table cellspacing=\"0\" cellpadding=\"5\" rules=\"all\" border=\"1\">");

StringBuilder sHead = new StringBuilder();

sHead.Append("<tr style=\"font-weight: bold; white-space: nowrap; text-align=center;\">");

string[] columnName = { "出处", "创建时间", "标题", "报告分类", "ID", "分类名称", "用户编码", "信息时间", "修改时间", "状态" };

for (int i = 0; i < columnName.Length; i++)             {

sHead.AppendFormat("<td>{0}</td>", columnName[i]);

}

sHead.Append("</tr>");

//获取要导出的数据(DataTable)

DataTable     data= bll.getdatetable();

if (data== null)

{

return "null";

}

StringBuilder sContent = new StringBuilder();

for (int i = 0; i < data.Rows.Count; i++)

{

sContent.Append("<tr align=\"center\">");

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["CHUCHU"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["CJSJ"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["XXBT"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["TYPEID"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["ID"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["TypeNAME"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["USERID"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["XXSJ"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["XGSJ"]);

sContent.AppendFormat("<td>{0}</td>", data.Rows[i]["Status"]);

sContent.Append("</tr>");

}

sBuilder.Append(sHead);

sBuilder.Append(sContent);

sBuilder.Append("</table>");

ExcelHelper excelHelper = new ExcelHelper();

bool result = excelHelper.saveAsExcel(sBuilder.ToString(), "资料文库");

return "";

}

#endregion

}

}

ExcelHelper.cs :

using System;

using System.Collections.Generic;

using System.Configuration;

using System.Data;

using System.Data.OleDb;

using System.IO;

using System.Web;

using System.Text;

using CNPC.Common.DataHelper;

namespace CNPC.Common.BaseHelper {

/// <summary>

/// Excel帮助类

/// </summary>

public class ExcelHelper     {

public ExcelHelper()

{ ;}

#region 应用数据库配置
        /// <summary>
        /// SqlServer数据库连接字符串
        /// </summary>
        public static string SqlConnectionString
        {
            get
            {
                //获取数据库连接字符串
                string sqlConnectionString = StringUtils.NotNullStr(ConfigurationManager.ConnectionStrings[Constants.SQLCONNECTIONSTRING], string.Empty);
                //判断连接字符串是否为空
                if (string.IsNullOrEmpty(sqlConnectionString))
                {
                    return string.Empty;
                }
                else
                {
                    //获取连接字符串是否加密
                    bool isConStringEncrypt = StringUtils.ToInt(ConfigurationManager.AppSettings[Constants.CONSTRINGENCRYPT]) == 1 ? true : false;
                    //判断是否对字符串加密
                    if (isConStringEncrypt)
                        sqlConnectionString = DESEncrypt.Decrypt(sqlConnectionString);
                    return sqlConnectionString;
                }
            }
        }
        #endregion

/// <summary>
        /// 返回非空字符串
        /// </summary>
        /// <param name="canNullStr"></param>
        /// <param name="defaultStr"></param>
        /// <returns></returns>
        public static string NotNullStr(object canNullStr, string defaultStr)
        {
            try
            {
                if ((canNullStr == null) || (canNullStr is DBNull))
                {
                    if (defaultStr != null)
                    {
                        return defaultStr;
                    }
                    return "";
                }
                return Convert.ToString(canNullStr);
            }
            catch
            {
                return defaultStr;
            }
        }

#region 一般配置
        /// <summary>
        /// 导入Excel时,服务器的临时文件夹
        /// </summary>
        public static string UploadTempFolderPath
        {
            get { return NotNullStr(ConfigurationManager.AppSettings[Constants.UPLOADTEMPFOLDERPATH], string.Empty); }
        }
        #endregion

#region 导入Excel

/// <summary>

/// 上传文件(true:上传成功;false:上传失败)

/// </summary>

/// <param name="postedFile">上传文件控件</param>

/// <param name="uploadPath">上传路径[ref]</param>

/// <returns></returns>

public bool UploadExcel(HttpPostedFile postedFile, ref string uploadPath)

{

//获取上传路径

uploadPath = UploadTempFolderPath;

uploadPath += "/" + Guid.NewGuid();

uploadPath = HttpContext.Current.Server.MapPath(uploadPath);

//上传文件

try

{

postedFile.SaveAs(uploadPath);

return true;

}

catch

{

return false;

}

}

/// <summary>

/// 获取excel的schema名称集合(返回List[string]集合)

/// </summary>

/// <param name="excelPath">excel路径</param>

/// <returns></returns>

public List<string> GetSchemaNameList(string excelPath)

{

//获取连接字符串

string oledbConString = GetConString(excelPath);

//如果Oledb连接字符串为空

if (string.IsNullOrEmpty(oledbConString))

return null;

else

{

using (OleDbConnection con = new OleDbConnection(oledbConString))

{

try

{

con.Open();//打开连接

//读取Excel中的数据

DataTable dt = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });

//关闭连接

con.Close();

//判断dt是否为空

if (dt == null)

return null;

else

{

//定以存放schema的容器

List<string> list = new List<string>();

//遍历dt

foreach (DataRow dr in dt.Rows)

{

string tableName = dr["TABLE_NAME"].ToString();

int tableNameLength = tableName.Length;

list.Add(tableName.Substring(0, tableNameLength - 1));

}

return list;

}

}

catch { return null; }

}

}

}

/// <summary>

/// 获取excel的数据(返回DataTable)

/// </summary>

/// <param name="schemaName">schema名称</param>

/// <param name="startRow">开始行</param>

/// <param name="endRow">结束行</param>

/// <param name="excelPath">excel路径</param>

/// <returns></returns>

public DataTable GetExcelData(string schemaName, int startRow, int endRow, string excelPath)

{

try

{

//根据schema名称和excel路径获取当前schema的数据

DataTable dt = GetExcelData(schemaName, excelPath);

if (dt == null)

return null;

else

{

//判断选定的读取行是否超过索引上限

if (dt.Rows.Count < endRow || startRow > endRow)

return null;

else

{

//创建新的DataTable

DataTable newDt = new DataTable();

//设置newDt的列

for (int i = 0; i < dt.Columns.Count; i++)

{

DataColumn dc = new DataColumn(i.ToString());

newDt.Columns.Add(dc);

}

//获取dt的列数

int columnCount = dt.Columns.Count;

//遍历DataTable的数据

for (int i = startRow - 1; i <= endRow - 1; i++)

{

//实例化对象数组,长度为DataTable的列数量

object[] obj = new object[columnCount];

for (int j = 0; j < columnCount; j++)

{

obj.SetValue(dt.Rows[i][j], j);

}

newDt.Rows.Add(obj);

}

//删除临时文件

DeleteExcel(excelPath);

return newDt;

}

}

}

catch

{

return null;

}

}

/// <summary>

/// 根据schema名称和excel路径获取当前schema的数据

/// </summary>

/// <param name="schemaName">schema名称</param>

/// <param name="excelPath">excel路径</param>

/// <returns></returns>

private DataTable GetExcelData(string schemaName, string excelPath)

{

//获取连接字符串

string oledbConString = GetConString(excelPath);

//如果Oledb连接字符串为空

if (string.IsNullOrEmpty(oledbConString))

return null;

else

{

using (OleDbConnection con = new OleDbConnection(oledbConString))

{

try

{

string sqlString = "select * from [" + schemaName + "$]";

DataSet ds = new DataSet();

OleDbDataAdapter da = new OleDbDataAdapter(sqlString, con);

da.Fill(ds);

return ds.Tables[0];

}

catch { return null; }

}

}

}

/// <summary>

/// 获取连接字符串

/// </summary>

/// <param name="excelPath">excel路径</param>

/// <returns></returns>

private string GetConString(string excelPath)

{

string connString = SqlConnectionString;

connString = string.Format(connString, excelPath);

return connString;

}

/// <summary>

/// 根据文件路径删除文件

/// </summary>

/// <param name="ExcelPath"></param>

private void DeleteExcel(string excelPath)

{

//判断文件是否存在

if (File.Exists(excelPath))

{

//删除文件

File.Delete(excelPath);

}

}

#endregion

#region 将html内容另存为Excel

/// <summary>

/// 将html内容另存为Excel

/// </summary>

/// <param name="content">html格式的内容字符串</param>

/// <param name="xlsFile">要保存的Excel文件名</param>

/// <returns></returns>

public  bool saveAsExcel(string content, string xlsFile)

{

try

{

string html = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=gb2312\">" + content;

System.Web.HttpContext curContext = System.Web.HttpContext.Current;

curContext.Response.Buffer = true;

curContext.Response.Clear();

curContext.Response.Charset = "GB2312";

if (curContext.Request.UserAgent.Contains("MSIE") || curContext.Request.UserAgent.Contains("msie"))

{

// 如果客户端使用 Microsoft Internet Explorer,则需要编码

// 如果使用 fileName =Server.UrlEncode(fileName); 则会出现上文中出现的情况

xlsFile = toHexString(xlsFile);

}

curContext.Response.AppendHeader("Content-Disposition", "attachment;filename=" + xlsFile + ".xls");

curContext.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

//设置输出流为简体中文

curContext.Response.ContentType = "application/ms-excel";

//设置输出文件类型为excel文件。

curContext.Response.Write(html);

curContext.Response.Flush();

curContext.Response.Clear();

//curContext.Response.End();

curContext.ApplicationInstance.CompleteRequest();

}

catch (Exception ex)

{

return false;

}

return true;

}

// 为字符串中的非英文字符编码

string toHexString(string s)         {

char[] chars = s.ToCharArray();

StringBuilder builder = new StringBuilder();

for (int index = 0; index < chars.Length; index++)

{

bool bEncode = needToEncode(chars[index]);

if (bEncode)

{

string encodedString = toHexString(chars[index]);

builder.Append(encodedString);

}

else

{

builder.Append(chars[index]);

}

}

return builder.ToString();

}

//指定 一个字符是否应该被编码

bool needToEncode(char chr)

{

string reservedChars = "$-_.+!*‘(),@=&";

if (chr > 127)

return true;

if (char.IsLetterOrDigit(chr) || reservedChars.IndexOf(chr) >= 0)

return false;

return true;

}

// 为非英文字符串编码

string toHexString(char chr)

{

UTF8Encoding utf8 = new UTF8Encoding();

byte[] encodedBytes = utf8.GetBytes(chr.ToString());

StringBuilder builder = new StringBuilder();

for (int index = 0; index < encodedBytes.Length; index++)

{

builder.AppendFormat("%{0}", Convert.ToString(encodedBytes[index], 16));

}

return builder.ToString();

}

#endregion

}

}

时间: 2024-08-09 02:15:30

c# Excel导出的相关文章

displaytag的Excel导出实践

本文转自 http://lingceng.iteye.com/blog/1820081/ Displaytag官网有1.0, 1.1, 1.2等,注意找到对应的版本.源码和API可以在Maven库中找到.   常规的使用不是问题,这里说说关于Excel导出的问题,中文乱码,使用POI等.我使用的是Displaytag1.1. 基本导出功能   这种情况只需引入displaytag-1.1.jar.   设置column属性media="html"将不会导出,media="ex

ExtJS实现Excel导出

1. 使用POI组件实现excel导出功能 //获取问题列表 List<Suggestion> targetStockList = suggestionService.getSuggestionList(map);           //创建一个新的Excel         HSSFWorkbook workBook = new HSSFWorkbook();         //创建sheet页         HSSFSheet sheet = workBook.createSheet

二十六、【开源框架】EFW框架Winform前端开发之Grid++Report报表、条形码、Excel导出、图表控件

回<[开源]EFW框架系列文章索引>        EFW框架源代码下载V1.2:http://pan.baidu.com/s/1hcnuA EFW框架实例源代码下载:http://pan.baidu.com/s/1o6MAKCa 前言:本章介绍除DotNetBar2控件套件之外的另外一些常用控件,包括Grid++Report报表.条形码.Excel导出.图表控件ZedGraph:类似这些控件网上免费开源的太少了,经过一番对比和使用感受最后决定把这几个控件整合到EFW框架中供大家选择使用: 本

java excel导出

1.  Excel导出的核心方法在ExportExcel类中,使用时请将该类完整的引入. 1 import java.io.IOException; 2 import java.io.OutputStream; 3 import java.lang.reflect.Field; 4 import java.lang.reflect.InvocationTargetException; 5 import java.lang.reflect.Method; 6 import java.text.Si

利用Aspose.Cells完成easyUI中DataGrid数据的Excel导出功能

我准备在项目中实现该功能之前,google发现大部分代码都是利用一般处理程序 HttpHandler实现的服务器端数据的Excel导出,但是这样存在的问题是ashx读取的数据一般都是数据库中视图的数据,难免会含有方便操作的 主键ID这列的记录.现在项目需要在easyUI的DataGrid中显示的数据能全部导出Excel,包括DataGrid中的中文标题,其他的统统不 要. 完成该功能所需的工具和环境:Newtonsoft.Json序列化和反序列化类库.easyUI前端UI框架.HttpHandl

excel导出功能优化

先说说优化前,怎么做EXCEL导出功能的: 1. 先定义一个VO类,类中的字段按照EXCEL的顺序定义,并且该类只能用于EXCEL导出使用,不能随便修改. 2. 将查询到的结果集循环写入到这个VO类中. 3. 将这个VO类的数据集写入到EXCEL中. 缺点: 1.每次做一个功能的excel导出需要定义一个vo类,并且vo类不可随便变更. 2. 从数据库查询到结果集不能直接输出到excel,需要二次遍历写入到vo中. 3. excel导出的顺序必须与vo定义的字段顺序一致,并且输出vo中所有的字段

偷懒小工具 - Excel导出公共类

说明 最近接了一个任务,就是做一个列表的Excel导出功能.并且有很多页面都会使用这个功能. 导出的Excel大体格式如图 很简单的列表,标题加背景色,然后不同类型,显示方式不一样.对齐方式不一样.不同页面除了内容以外,大体形式都差不多. 当时本来是想直接用NPOI,IRow ICell.这样进行拼接页面,最简单也最方便. 但是很多页面,都进行这种类似的设计.我实在是懒得做这种重复功能.所以花了一点时间,整理了一下帮助类. 使用 做好这个帮助类以后只要进行两点调用 1.制作导出Excel的数据模

java反射学习之二万能EXCEL导出

一.EXCEL导出的实现过程 假设有一个对象的集合,现在需要将此集合内的所有对象导出到EXCEL中,对象有N个属性:那么我们实现的方式是这样的: 循环这个集合,在循环集合中某个对象的所有属性,将这个对象的所有属性作为EXCEL的列,该对象占据EXCEL的一行 二.万能EXCEL导出(以JXL为例,jxl.poi等excel导入导出的jar包不做介绍了) 1.创建java工程.引入jxl的jar包 2.直接上代码 Book.java /** * Book对象 * @author bwy * */

(Excel导出失败)检索COM类工厂中CLSID为{00024500-0000-0000-C000-000000000046}的组件时失

在DCOM 中不存在WORD.EXCEL等OFFICE组件 最近在做一个关于office转存PDF的Web项目.开发过程一切顺利. 起初在网上找到一些Word,PPT转PDF的代码.很好用.一切顺利项目开发成功.在这里需要说明一点,PPT中会存在流媒体内容,如果存在这些内容的时候是不能成功转换为PDF的.需要手动将相关内容删除后才可以转换.各位如果遇到些奇怪的问题的时候,希望检查下PPT中是不是存在这些内容. 项目开发结束,问题就来了.因为需要搭建测试环境.就拿手边一台防止的机器搭建了测试环境.

txt excel 导出 文件名称为中文,避免乱码的解决方案

在通过response导出文件数据的时候,不论是txt 还是Excel ,如果想让其文件名称为中文,解决方案: response.setCharacterEncoding("UTF-8"); response.setContentType("application/txt");//"application/vnd.ms-excel" response.setHeader("Content-disposition","