/// <summary>
/// 导出为Excel
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void btnExport_Click(object sender, EventArgs e)
{
ExportTest();
}

/// <summary>
/// 导出测试
/// </summary>
protected void ExportTest()
{
ExcelXML excel = new ExcelXML();
//excel.Sheets.Add("Sheet1");
//excel.Sheets.Add("Sheet5");
//excel.Sheets.Add("工作表1");
//excel.Sheets[0].Rows.AddTitle(new string[] { "编号", "部门", "日期" }, new ValueType[] { ValueType.Number, ValueType.String, ValueType.String });
//excel.Sheets[0].Frozen(0, 1);
//excel.Sheets[0].Rows.Add(new string[] { "1a", "财务部", "2009-1-5" });
//excel.Sheets[0].Rows.Add(new string[] { "02", "市场部", "2010-01-20 15:35" });
//excel.Sheets[0].Rows.Add(new string[] { "3", "销售部", "15:20:37" });
//excel.Sheets[0].Rows.Add(new string[] { "", "销售部", "15:20:37" });
//excel.Sheets[0].Rows.Add(new string[] { "0", "销售部", "15:20:37" });
//excel.Sheets[0].Rows.Add(new string[] { "1234567890", "销售部", "15:20:37" });
//excel.Sheets[0].Rows.Add(new string[] { "12345678901", "销售部", "15:20:37" });
//excel.Sheets[0].Rows.Add(new string[] { "123456789012", "销售部", "15:20:37" });

//excel.Sheets[1].Rows.Add(new string[] { "1", "2", "3" });
//excel.Sheets[1].Rows.Add(new string[] { "1", "测字测试", "3" });
//excel.Sheets[1].Frozen(1, 0);

//excel.Sheets[2].Rows.Add(new string[] { "1", "2", "3" });
//excel.Sheets[2].Rows.Add(new string[] { "1", "测字测试", "3" });

Sheet sheet = new Sheet("测试");
sheet.Rows.AddTitle(new string[] { "编号", "部门", "日期", "值" });
for (int i = 1; i < 100; i++)
{
sheet.Rows.Add(new string[] { i.ToString(), "部门_" + i % 3, DateTime.Today.AddDays(i % 5).ToString(), (i * 100).ToString() });
}
sheet.Frozen(2, 1);
excel.Sheets.Add(sheet);

excel.Export(DateTime.Now.ToString("yyyyMMdd-HHmmss_") + "Export");
}

===========================================================================================================

using System;
using System.Web;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;

namespace ExportExcel
{
/// <summary>
/// 单元格值类型(日期作为文本处理)
/// </summary>
public enum ValueType
{
String = 0,
Number = 1
}

/// <summary>
/// 行
/// </summary>
public class Row
{
private static string _patten = @"^\d{1,15}$";
private static Regex _regex = new Regex(_patten);
private string[] _cellsValue;
public string[] CellsValue
{
get { return _cellsValue; }
set { _cellsValue = value; }
}

private string _rowText;
public string RowText
{
get { return _rowText; }
}

/// <summary>
/// 构造函数,生成一行
/// </summary>
/// <param name="values">各单元格值</param>
/// <param name="isAutoType">是否自动设置值类型</param>
public Row(string[] values, bool isAutoType)
{
if (values.Length > 256)
{
throw new Exception("Excel中不能超过256列!");
}

_cellsValue = values;

_rowText = "<Row>\n";
foreach (string cell in values)
{
ValueType vType = ValueType.String;
if (isAutoType)
{
if (_regex.Match(cell).Success)
{
vType = ValueType.Number;
}
}
_rowText += "<Cell><Data ss:Type=\"" + vType.ToString() + "\">" + cell + "</Data></Cell>\n";
}
_rowText += "</Row>\n";
}

/// <summary>
/// 构造函数,生成一行
/// </summary>
/// <param name="values">各单元格值</param>
/// <param name="valueTypes">各单元格值类型</param>
public Row(string[] values, ValueType[] valueTypes)
{
if (values.Length > 256 || valueTypes.Length > 256)
{
throw new Exception("Excel中不能超过256列!");
}

_cellsValue = values;

int i = 0;
_rowText = "<Row>\n";
foreach (string cell in values)
{
ValueType vType = ValueType.String;
if (i<valueTypes.Length)
{
vType = valueTypes[i];
if (vType == ValueType.Number)
{
if (!_regex.Match(cell).Success)
{
vType = ValueType.String;
}
}
}
_rowText += "<Cell><Data ss:Type=\"" + vType.ToString() + "\">" + cell + "</Data></Cell>\n";

i++;
}
_rowText += "</Row>\n";
}
}

/// <summary>
/// 行集合
/// </summary>
public class _rows : IEnumerable
{
private List<Row> _rowList = new List<Row>();
private bool _isAutoType = true;
public bool IsAutoType
{
get { return _isAutoType; }
set { _isAutoType = value; }
}

private ValueType[] _valueTypes;
public ValueType[] ValueTypes
{
get { return _valueTypes; }
set { _valueTypes = value; }
}

/// <summary>
/// 已使用行数
/// </summary>
public int Count
{
get { return _rowList.Count; }
}

/// <summary>
/// 添加标题行
/// </summary>
/// <param name="cells"></param>
/// <param name="valueTypes"></param>
/// <returns></returns>
public Row AddTitle(string[] cells)
{
Row row = new Row(cells, false);
_rowList.Add(row);
return row;
}

/// <summary>
/// 添加标题行并设置列格式
/// </summary>
/// <param name="cells"></param>
/// <param name="valueTypes"></param>
/// <returns></returns>
public Row AddTitle(string[] cells, ValueType[] valueTypes)
{
this._valueTypes = valueTypes;
Row row = new Row(cells, false);
_rowList.Add(row);
return row;
}

/// <summary>
/// 添加行
/// </summary>
/// <param name="cells"></param>
public Row Add(string[] cells)
{
if (this.Count >= 65536)
{
throw new Exception("已经达到了Excel允许的最大行!");
}

if (_valueTypes == null)
{
Row row = new Row(cells, _isAutoType);
_rowList.Add(row);
return row;
}
else
{
Row row = new Row(cells, _valueTypes);
_rowList.Add(row);
return row;
}
}

/// <summary>
/// 删除行
/// </summary>
/// <param name="index">行号</param>
public void Delete(int index)
{
if (index < 0 || index >= this.Count)
{
throw new Exception("下标超出范围!");
}
_rowList.RemoveAt(index);
}

/// <summary>
/// 获取行
/// </summary>
/// <param name="index">行号</param>
/// <returns></returns>
public Row this[int index]
{
get
{
if (index<0 || index >= this.Count)
{
throw new Exception("下标超出范围!");
}
return _rowList[index];
}
}

/// <summary>
/// 遍历行
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return _rowList.GetEnumerator();
}
}

/// <summary>
/// 工作表类
/// </summary>
public class Sheet
{
private string _sheetName;
public string SheetName
{
get { return _sheetName; }
set { _sheetName = value; }
}

private int _topRowBottomPane = 0;
public int TopRowBottomPane
{
get { return _topRowBottomPane; }
}

private int _leftColumnRightPane = 0;
public int LeftColumnRightPane
{
get { return _leftColumnRightPane; }
}

/// <summary>
/// 构造工作表
/// </summary>
/// <param name="sheetName">工作表名</param>
public Sheet(string sheetName)
{
this._sheetName = sheetName;
}

/// <summary>
/// 冻结窗格
/// </summary>
/// <param name="topRowBottomPane">冻结线上方行数</param>
/// <param name="leftColumnRightPane">冻结线左边行数</param>
public void Frozen(int topRowBottomPane, int leftColumnRightPane)
{
if (topRowBottomPane < 0 || topRowBottomPane >= 65536)
{
throw new Exception("索引超出范围!");
}
if (leftColumnRightPane < 0 || leftColumnRightPane >= 256)
{
throw new Exception("索引超出范围!");
}

this._topRowBottomPane = topRowBottomPane;
this._leftColumnRightPane = leftColumnRightPane;
}

public _rows Rows = new _rows();

}

/// <summary>
/// 工作表集合
/// </summary>
public class _sheets: IEnumerable
{
private List<Sheet> _sheetList = new List<Sheet>();

/// <summary>
/// 工作表数量
/// </summary>
public int Count
{
get { return _sheetList.Count; }
}

/// <summary>
/// 添加工作表
/// </summary>
/// <param name="sheetName">工作表名</param>
/// <returns>工作表对象</returns>
public Sheet Add(string sheetName)
{
foreach (Sheet sht in _sheetList)
{
if (sht.SheetName == sheetName)
{
throw new Exception("同一工作簿中工作表名不能相同!");
}
}

Sheet sheet = new Sheet(sheetName);
_sheetList.Add(sheet);
return sheet;
}

/// <summary>
/// 添加工作表
/// </summary>
/// <param name="sheet">工作表对象</param>
/// <returns>工作表对象</returns>
public Sheet Add(Sheet sheet)
{
foreach (Sheet sht in _sheetList)
{
if (sht.SheetName == sheet.SheetName)
{
throw new Exception("同一工作簿中工作表名不能相同!");
}
}

_sheetList.Add(sheet);
return sheet;
}

/// <summary>
/// 删除工作表
/// </summary>
/// <param name="index">工作表索引</param>
public void Delete(int index)
{
if (index < 0 || index >= this.Count)
{
throw new Exception("下标超出范围!");
}
_sheetList.RemoveAt(index);
}

/// <summary>
/// 获取工作表
/// </summary>
/// <param name="index">工作表索引</param>
/// <returns></returns>
public Sheet this[int index]
{
get
{
if (index < 0 || index >= this.Count)
{
throw new Exception("下标超出范围!");
}
return _sheetList[index];
}
}

/// <summary>
/// 遍历工作表
/// </summary>
/// <returns></returns>
public IEnumerator GetEnumerator()
{
return _sheetList.GetEnumerator();
}
}

/// <summary>
/// Excel XML工作簿类
/// </summary>
public class ExcelXML
{
public _sheets Sheets = new _sheets();

private static string _appHead = "<?xml version=\"1.0\"?> \n<?mso-application progid=\"Excel.Sheet\"?>\n";
private static string _workBookHead = "<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\" \n xmlns:o=\"urn:schemas-microsoft-com:office:office\" \n xmlns:x=\"urn:schemas-microsoft-com:office:excel\" \n xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\" \n xmlns:html=\"http://www.w3.org/TR/REC-html40\"> \n\n";

#region 冻结窗格

/// <summary>
/// 设置工作表选项
/// </summary>
/// <param name="topRowBottomPane"></param>
/// <param name="leftColumnRightPane"></param>
/// <returns></returns>
private string GetWorksheetOptions(int topRowBottomPane, int leftColumnRightPane)
{
string s = "";

if (topRowBottomPane + leftColumnRightPane <= 0)
{
return s;
}

s += "<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\n";
s += "<Selected/>";
s += "<FreezePanes/>\n";
s += "<FrozenNoSplit/>\n";

//冻结行
if (topRowBottomPane > 0 && leftColumnRightPane <= 0)
{
s += "<SplitHorizontal>" + topRowBottomPane + "</SplitHorizontal>\n";
s += "<TopRowBottomPane>" + topRowBottomPane + "</TopRowBottomPane>\n";
//s += "<ActivePane>2</ActivePane>\n";
//s += "<Panes>\n<Pane>\n<number>3</Number>\n</Pane>\n<Pane>\n<number>2</Number>\n</Pane>\n</Panes>\n";

}
//冻结列
else if (leftColumnRightPane > 0 && topRowBottomPane <= 0)
{
s += "<SplitVertical>" + leftColumnRightPane + "</SplitVertical>\n";
s += "<LeftColumnRightPane>" + leftColumnRightPane + "</LeftColumnRightPane>\n";
//s += "<ActivePane>2</ActivePane>\n";
//s += "<Panes>\n<Pane>\n<number>5</Number>\n</Pane>\n<Pane>\n<number>2</Number>\n</Pane>\n</Panes>\n";
}
//冻结行、列
else
{
s += "<SplitHorizontal>" + topRowBottomPane + "</SplitHorizontal>\n";
s += "<TopRowBottomPane>" + topRowBottomPane + "</TopRowBottomPane>\n";
s += "<SplitVertical>" + leftColumnRightPane + "</SplitVertical>\n";
s += "<LeftColumnRightPane>" + leftColumnRightPane + "</LeftColumnRightPane>\n";
s += "<ActivePane>0</ActivePane>\n";
s += "<Panes>\n<Pane>\n<Number>3</Number>\n</Pane>\n<Pane>\n<Number>1</Number>\n</Pane>\n<Pane>\n<Number>2</Number>\n</Pane>\n<Pane>\n<Number>0</Number>\n</Pane>\n</Panes>\n";
}

s += "<ProtectObjects>False</ProtectObjects>\n";
s += "<ProtectScenarios>False</ProtectScenarios>\n";
s += "</WorksheetOptions>\n";

return s;
}

#endregion

/// <summary>
/// 导出到文件
/// </summary>
/// <param name="fileName"></param>
public void Export(string fileName)
{
if (this.Sheets.Count < 1)
{
throw new Exception("没有工作表!");
}

string fName = System.Web.HttpUtility.UrlEncode(System.Text.Encoding.UTF8.GetBytes(fileName));
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + fName + ".xls");
HttpContext.Current.Response.Charset = "UTF-8";
HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.UTF8;
HttpContext.Current.Response.ContentType = "application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword

HttpContext.Current.Response.Write(_appHead);
HttpContext.Current.Response.Write(_workBookHead);

//遍历工作表
foreach (Sheet sht in Sheets)
{
HttpContext.Current.Response.Write("<Worksheet ss:Name=\"" + sht.SheetName + "\">\n");
HttpContext.Current.Response.Write("<Table>\n");

//遍历行
foreach (Row row in sht.Rows)
{
HttpContext.Current.Response.Write("\n" + row.RowText);
}

HttpContext.Current.Response.Write("\n</Table>\n");

//冻结窗格选项
string sheetOptions = GetWorksheetOptions(sht.TopRowBottomPane, sht.LeftColumnRightPane);
HttpContext.Current.Response.Write(sheetOptions);

HttpContext.Current.Response.Write("</Worksheet>\n");
}

HttpContext.Current.Response.Write("</Workbook>\n");
HttpContext.Current.Response.End();
}
}
}

服务器不安装Excel,实现导出Excel功能的更多相关文章

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

    excel 基础 •整个excel 表格叫工作表:workbook:工作表包含的叫页:sheet:行:row:单元格:cell. •excel 中的电话号码问题,看起来像数字的字符串以半角单引号开头就 ...

  2. [转]Excel.dll 导出Excel控制

    Excel.dll 导出Excel控制 2010-06-12 11:26 2932人阅读 评论(2) 收藏 举报 excelmicrosoftstring产品服务器google 最近做了个导出Exce ...

  3. ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案 try.dot.net 的正确使用姿势 .Net NPOI 根据excel模板导出excel、直接生成excel .Net NPOI 上传excel文件、提交后台获取excel里的数据

    ASP.NET Core 2.2 : 十六.扒一扒新的Endpoint路由方案   ASP.NET Core 从2.2版本开始,采用了一个新的名为Endpoint的路由方案,与原来的方案在使用上差别不 ...

  4. .Net NPOI 根据excel模板导出excel、直接生成excel

    一.根据Excel模板导出excel 1.导入NPOI.dll  2.DAL中添加类ExportExcel.cs using NPOI.SS.UserModel; using System; usin ...

  5. 纳税服务系统【用户模块之使用POI导入excel、导出excel】

    前言 再次回到我们的用户模块上,我们发现还有两个功能没有完成: 对于将网页中的数据导入或导出到excel文件中,我们是完全没有学习过的.但是呢,在Java中操作excel是相对常用的,因此也有组件供我 ...

  6. C#导出EXCEL(DataTable导出EXCEL)

    using System; using System.Collections.Generic; using System.Text; using System.Data; using System.I ...

  7. [poi使用]使用excel模版导出excel

    ​ Apache POI是基于Office Open XML标准(OOXML)和Microsoft的OLE 2复合文档格式(OLE2)处理各种文件格式的开源项目.简而言之,您可以使用Java读写MS ...

  8. poi根据excel模板导出Excel

    /****单元格值对象**/public class Cells { /*** * 行 */ private int row; /** * 列 */ private int column; /** * ...

  9. java实现把对象数组通过excel方式导出的功能

    一.导入相关jar包,pom依赖如下: <dependency> <groupId>org.apache.poi</groupId> <artifactId& ...

  10. 【Java excel】导出excel文件

    TestExprot package excel; import java.io.File; import java.io.IOException; import java.text.DateForm ...

随机推荐

  1. PAT——乙级1028

    这道题花了我半个多小时,对呀乙级算是挺多时间的了. 1028 人口普查 (20 point(s)) 某城镇进行人口普查,得到了全体居民的生日.现请你写个程序,找出镇上最年长和最年轻的人. 这里确保每个 ...

  2. linux服务器基本安全配置手册

    转:忘了在哪转的,直接复制到笔记里了,贴出来分享 假如你想要搭建一个Linux服务器,并且希望可以长期维护的话,就需要考虑安全性能与速度等众多因素.一份正确的linux基本安全配置手册就显得格外重要. ...

  3. 【bzoj4636】蒟蒻的数列 离散化+线段树

    原文地址:http://www.cnblogs.com/GXZlegend/p/6801379.html 题目描述 蒟蒻DCrusher不仅喜欢玩扑克,还喜欢研究数列 题目描述 DCrusher有一个 ...

  4. NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet

    springMVC 内嵌jetty时,出现了NO JSP Support for /, did not find org.eclipse.jetty.jsp.JettyJspServlet: 添加了 ...

  5. DataBase -- Note I

    SQL对大小写不敏感! SQL DML和DDL:可以把SQL分为两个部分:数据操作语言(DML)和数据定义语言(DDL) SQL(结构化查询语言)是用于执行查询的语法.但是SQL语言也包含用于更新.插 ...

  6. CentOS 7添加本地回环地址

    CentOS 7添加本地回环地址 1. 临时添加ip addr add 10.10.1.1/32 dev lo:1重启失效2.永久添加cd /etc/sysconfig/network-scripts ...

  7. The UVALIVE 7716 二维区间第k小

    The UVALIVE 7716 二维区间第k小 /** 题意:给一个n * n的矩阵,有q个查询 每次查询r,c,s,k表示已(r,c)为右上角 大小为s的正方形中 第k小的元素 n <= 2 ...

  8. php的post

    代码的顺序不能乱,否则会提交错误 $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HE ...

  9. POJ3984 BFS广搜--入门题

    迷宫问题 Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 20816   Accepted: 12193 Descriptio ...

  10. [ CodeVS冲杯之路 ] P1294

    不充钱,你怎么AC? 题目:http://codevs.cn/problem/1294/ 随手一打就是这么漂亮的全排列,想当年我初一还是初二的时候,调了1个多小时才写出来(蒟蒻一枚) 直接DFS每次枚 ...