自定义Excel导出简易组件
1.组件原理
excel的数据存储是以xml格式存储的,所以导出Excel文件可以通过生成XML来实现。当然XML必须符合一定的格式要求。
2.组件实现
(1)新建类库文件“MyExcel”
(2)添加类型“WorkBook”,这里指Excel的工作表。
namespace MyExcel
{
public class WorkBook
{
private StringBuilder excelstr;
private List<WorkSheet> sheets;
public WorkBook()
{
this.excelstr = new StringBuilder();
this.sheets = new List<WorkSheet>();
}
public WorkSheet CreateSheet(string title)
{
if (sheets == null)
{
throw new Exception("只有先构建WorkBook对象后才能构建WorkSheet对象!");
}
foreach (WorkSheet sht in sheets)
{
if (sht.Title.ToLower() == title.ToLower())
{
throw new Exception("已经有名称为:" + title + " 的Sheet");
}
}
WorkSheet wsheeet = new WorkSheet(title);
this.sheets.Add(wsheeet);
return wsheeet;
}
private string WriteWorkBook()
{
if (sheets == null || sheets.Count < )
{
throw new Exception("只有先构建WorkBook对象后才能构建行对象!");
}
excelstr.Append("<?xml version=\"1.0\"?>\r\n");
excelstr.Append("<?mso-application progid=\"Excel.Sheet\"?>\r\n");
excelstr.Append("<Workbook xmlns=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n");
excelstr.Append("xmlns:o=\"urn:schemas-microsoft-com:office:office\"\r\n");
excelstr.Append("xmlns:x=\"urn:schemas-microsoft-com:office:excel\"\r\n");
excelstr.Append("xmlns:ss=\"urn:schemas-microsoft-com:office:spreadsheet\"\r\n");
excelstr.Append("xmlns:html=\"http://www.w3.org/TR/REC-html40\">\r\n");
excelstr.Append("<DocumentProperties xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n");
excelstr.Append("<Created>2006-09-16T00:00:00Z</Created>\r\n");
excelstr.Append("<LastSaved>2015-07-07T05:50:29Z</LastSaved>\r\n");
excelstr.Append("<Version>14.00</Version>\r\n");
excelstr.Append("</DocumentProperties>\r\n");
excelstr.Append("<OfficeDocumentSettings xmlns=\"urn:schemas-microsoft-com:office:office\">\r\n");
excelstr.Append("<AllowPNG/>\r\n");
excelstr.Append("<RemovePersonalInformation/>\r\n");
excelstr.Append("</OfficeDocumentSettings>\r\n");
excelstr.Append("<ExcelWorkbook xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n");
excelstr.Append("<WindowHeight>8010</WindowHeight>\r\n");
excelstr.Append("<WindowWidth>14805</WindowWidth>\r\n");
excelstr.Append("<WindowTopX>240</WindowTopX>\r\n");
excelstr.Append("<WindowTopY>105</WindowTopY>\r\n");
excelstr.Append("<ProtectStructure>False</ProtectStructure>\r\n");
excelstr.Append("<ProtectWindows>False</ProtectWindows>\r\n");
excelstr.Append("</ExcelWorkbook>\r\n");
excelstr.Append("<Styles>\r\n");
excelstr.Append("<Style ss:ID=\"Default\" ss:Name=\"Normal\">\r\n");
excelstr.Append("<Alignment ss:Vertical=\"Bottom\"/>\r\n");
excelstr.Append("<Borders/>\r\n");
excelstr.Append("<Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"11\" ss:Color=\"#000000\"/>\r\n");
excelstr.Append("<Interior/>\r\n");
excelstr.Append("<NumberFormat/>\r\n");
excelstr.Append("<Protection/>\r\n");
excelstr.Append("</Style>\r\n");
excelstr.Append("<Style ss:ID=\"s64\">\r\n");
excelstr.Append("<Alignment ss:Horizontal=\"Center\" ss:Vertical=\"Center\"/>\r\n");
excelstr.Append("<Font ss:FontName=\"宋体\" x:CharSet=\"134\" ss:Size=\"11\" ss:Color=\"#000000\"\r\n");
excelstr.Append("ss:Bold=\"1\"/>\r\n");
excelstr.Append("</Style>\r\n");
excelstr.Append("</Styles>\r\n");
foreach (WorkSheet item in sheets)
{
excelstr.Append(item.WriteSheet());
}
excelstr.Append("</Workbook>\r\n");
return excelstr.ToString();
}
/// <summary>
/// Write Data To Stream.
/// </summary>
/// <param name="ms"></param>
public void WriteStream(Stream ms)
{
try
{
string msg = WriteWorkBook();
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
ms.Write(buffer, , buffer.Length); }
catch (Exception)
{
throw new Exception("写入流错误");
} }
}
}
(3)添加类型“WorkSheet”,这里指Excel的工作簿。
namespace MyExcel
{
public class WorkSheet
{
private List<Row> rowcollection;
private string title = "";
internal WorkSheet(string title)
{
this.title = title;
this.rowcollection = new List<Row>();
}
internal string Title
{ get { return title; } }
public Row CreateRow()
{
Row _row = new Row();
if (this.rowcollection == null)
{
throw new Exception("只有先构建Sheet对象后才能构建行对象!");
}
rowcollection.Add(_row);
return _row;
} internal string WriteSheet()
{
if (rowcollection == null || rowcollection.Count < )
{
throw new Exception("未添加行(Row)对象");
}
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("<Worksheet ss:Name=\"{0}\">\r\n", title));
sb.Append("<Table ss:ExpandedColumnCount=\"200\" ss:ExpandedRowCount=\"65535\" x:FullColumns=\"1\"\r\n");
sb.Append("x:FullRows=\"1\" ss:DefaultColumnWidth=\"54\" ss:DefaultRowHeight=\"13.5\">\r\n"); foreach (Row _row in rowcollection)
{
sb.Append(_row.WriteRow());
}
sb.Append("</Table>\r\n");
sb.Append("<WorksheetOptions xmlns=\"urn:schemas-microsoft-com:office:excel\">\r\n");
sb.Append("<PageSetup>\r\n");
sb.Append("<Header x:Margin=\"0.3\"/>\r\n");
sb.Append("<Footer x:Margin=\"0.3\"/>\r\n");
sb.Append("<PageMargins x:Bottom=\"0.75\" x:Left=\"0.7\" x:Right=\"0.7\" x:Top=\"0.75\"/>\r\n");
sb.Append("</PageSetup>\r\n");
sb.Append("<Print>\r\n");
sb.Append("<ValidPrinterInfo/>\r\n");
sb.Append("<PaperSizeIndex>9</PaperSizeIndex>\r\n");
sb.Append("<HorizontalResolution>600</HorizontalResolution>\r\n");
sb.Append("<VerticalResolution>600</VerticalResolution>\r\n");
sb.Append("</Print>\r\n");
sb.Append("<Selected/>\r\n");
sb.Append("<ProtectObjects>False</ProtectObjects>\r\n");
sb.Append("<ProtectScenarios>False</ProtectScenarios>\r\n");
sb.Append("</WorksheetOptions>\r\n");
sb.Append("</Worksheet>\r\n");
return sb.ToString();
} }
}
(4)添加类型“Row”,这里指Sheet中的行。
namespace MyExcel
{
public class Row
{
private List<string> cells;
private List<string> headers;
internal Row()
{
this.cells = new List<string>();
this.headers = new List<string>();
}
/// <summary>
/// 添加列
/// </summary>
/// <param name="value"></param>
public void AddCell(string value)
{
cells.Add(value);
}
/// <summary>
/// 添加标题
/// </summary>
/// <param name="title"></param>
public void AddHeader(string title)
{
this.headers.Add(title);
}
internal string WriteRow()
{
if (cells == null)
{
if (headers == null)
{
throw new Exception("无单元格,请创建单元格");
}
else
{
if (headers.Count < )
{
throw new Exception("无单元格,请创建单元格");
}
}
}
else
{
if (headers == null)
{
if (cells.Count < )
{
throw new Exception("无单元格,请创建单元格");
}
}
else
{
if (headers.Count < &&cells.Count<)
{
throw new Exception("无单元格,请创建单元格");
}
}
}
StringBuilder sb = new StringBuilder();
if (headers!=null&&headers.Count>)
{
sb.Append("<Row>\r\n");
foreach (string item in headers)
{
sb.Append(string.Format("<Cell ss:StyleID=\"s64\"><Data ss:Type=\"String\">{0}</Data></Cell>\r\n", item));
}
sb.Append("</Row>\r\n");
}
if (cells != null && cells.Count > )
{
sb.Append("<Row>\r\n");
foreach (string item in cells)
{
sb.Append(string.Format("<Cell><Data ss:Type=\"String\">{0}</Data></Cell>\r\n", item));
}
sb.Append("</Row>\r\n");
}
return sb.ToString();
} } }
(5)编译类库文件,生成“MyExcel.dll”文件。
3.组件使用
添加引用,"MyExcel.dll"
(1)web程序使用
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MyExcel;
using System.IO; public partial class Default1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Clear();
Response.ClearHeaders();
Response.Buffer = true;
WorkBook wb = new WorkBook();//创建工作表
for (int j = ; j < ; j++)
{
WorkSheet ws = wb.CreateSheet("sheet"+(j+));//创建工作簿
Row r = ws.CreateRow();//创建ws的行
r.AddHeader("Name");//添加标题列
r.AddHeader("Sex");//添加标题列
r.AddHeader("Address");//添加标题列 for (int i = ; i < ; i++)
{
r = ws.CreateRow();//又创建一新行
r.AddCell("name" + (i + ));//添加列
r.AddCell("sex" + (i + ));//添加列
r.AddCell("address" + (i + ));//添加列
}
} MemoryStream ms = new MemoryStream();
wb.WriteStream(ms);//将xml数据写入内存流
byte[] buffer = ms.ToArray();
ms.Close();
//文件下载代码
Response.AddHeader("Content-Disposition", "attachment;filename=aa.xls");
Response.AddHeader("Contnet-Length", buffer.Length.ToString());
Response.ContentType = "application/ms-excel;charset=utf-8";
Response.ContentEncoding = System.Text.Encoding.GetEncoding("shift-jis");
Response.BinaryWrite(buffer);
}
}
(2)控制台程序
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
//构造工作表对象
WorkBook wb = new WorkBook();
//创建当前工作表的工作簿对象
WorkSheet ws = wb.CreateSheet("sheet1");
//创建当前工作簿的行对象
Row r = ws.CreateRow();
//当前行添加标题列
r.AddHeader("Name");
r.AddHeader("Sex");
r.AddHeader("Address");
for (int i = ; i < ; i++)
{
//创建新行
r = ws.CreateRow();
//添加新行的列
r.AddCell("name" + (i + ));
r.AddCell("sex" + (i + ));
r.AddCell("address" + (i + ));
}
MemoryStream ms = new MemoryStream();
//将数据写入内存流
wb.WriteStream(ms);
byte[] buffer = ms.ToArray();
FileStream fs = new FileStream(@"c:/aaa.xls", FileMode.Create, FileAccess.ReadWrite);
ms.Close();
fs.Write(buffer, , buffer.Length);
fs.Flush();
fs.Close();
Console.Read(); }
}
}
自定义Excel导出简易组件的更多相关文章
- 6、jeecg 笔记之 自定义excel 模板导出(一)
1.前言 jeecg 中已经自带 excel 的导出导出功能,其所使用的是 easypoi,尽管所导出的 excel 能满足大部分需求, 但总是有需要用到自定义 excel 导出模板,下文所用到的皆是 ...
- (Excel导出失败)检索COM类工厂中CLSID为{00024500-0000-0000-C000-000000000046}的组件时失
在DCOM 中不存在WORD.EXCEL等OFFICE组件 最近在做一个关于office转存PDF的Web项目.开发过程一切顺利. 起初在网上找到一些Word,PPT转PDF的代码.很好用.一切顺 ...
- java使用poi自定义excel标题头并导出(springmvc+poi)
项目使用的是jeecg开源框架(springmvc+spring+hibernate+......等)此代码仅供参考!如有更好的意见或建议可留言. 1 controller 层 /** * excel ...
- 并发编程概述 委托(delegate) 事件(event) .net core 2.0 event bus 一个简单的基于内存事件总线实现 .net core 基于NPOI 的excel导出类,支持自定义导出哪些字段 基于Ace Admin 的菜单栏实现 第五节:SignalR大杂烩(与MVC融合、全局的几个配置、跨域的应用、C/S程序充当Client和Server)
并发编程概述 前言 说实话,在我软件开发的头两年几乎不考虑并发编程,请求与响应把业务逻辑尽快完成一个星期的任务能两天完成绝不拖三天(剩下时间各种浪),根本不会考虑性能问题(能接受范围内).但随着工 ...
- 自定义分页Gridview中Excel导出
先上图,如图所示导出所有查询出的数据 用的是AspNetPager分页控件,这个导出方法,不受分页和gridview列中数据的约束,可以导出您想导出的数据 首先前台页面代码,lblink即为导出exc ...
- asp.net(C#) Excel导出类 导出.xls文件
---恢复内容开始--- using Microsoft.Office.Interop.Excel; 针对office 2003需添加引用Microsoft Excel 11.0 Obje ...
- 也谈Excel导出
吐槽 Excel导出在天朝的软件大环境下,差点成为软件开发必备.俺就遇到过,所有报表不提供导出功能,就能不验收的囧事.报表能查看能打印能形成图表已经完美,实在搞不懂导出excel有个毛用,但是公司依靠 ...
- Asp.Net 常用工具类之Office—Excel导出(4)
开发过程中各类报表导入导出防不胜防,网上也是各种解决方法层出不穷,比如Excel,CSV,Word,PDF,HTML等等... 网上各种导出插件也是层出不穷,NPOI,微软Microsoft.Offi ...
- C#Excel导出注意事项
Excel 导出 1.首先在服务器中安装office ,并且要注册2.在组件服务中 设置Microsoft.excel.appliction 属性中设置自定义加network service用户并交互 ...
随机推荐
- HDOJ(HDU) 2519 新生晚会(组合公式)
Problem Description 开学了,杭电又迎来了好多新生.ACMer想为新生准备一个节目.来报名要表演节目的人很多,多达N个,但是只需要从这N个人中选M个就够了,一共有多少种选择方法? I ...
- HDOJ 2011 多项式求和
Problem Description 多项式的描述如下: 1 - 1/2 + 1/3 - 1/4 + 1/5 - 1/6 + - 现在请你求出该多项式的前n项的和. Input 输入数据由2行组成, ...
- 邮件发送小demo
//send email public static bool SendEmail() { //实例化发件人地址 MailAddress from = new MailAddress("aa ...
- 网络编程——TCP协议的三次握手和四次挥手
三次握手原理解析 TCP握手协议在TCP/IP协议中,TCP协议提供可靠的连接服务,采用三次握手建立一个连接. 第一次握手:建立连接时,客户端发送syn包(syn=j)到服务器,并进入SYN_SEND ...
- [LeetCode] Largest Rectangle in Histogram 解题思路
Given n non-negative integers representing the histogram's bar height where the width of each bar is ...
- poj 2253 Frogger【最小生成树变形】【kruskal】
Frogger Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 30427 Accepted: 9806 Descript ...
- dvwa+xampp搭建显示乱码的问题:解决办法
如图,dvwa显示乱码,解决办法有两个:
- linux —— 启动引导程序 lilo 与 grub
目录:1.启动引导程序概要 2.lilo 的安装与配置 3.grub的安装与配置 4.两种引导程序的切换 5.附:编译内核时的lilo 设置 1.启动引导程序概要 2.lilo 的安装与配置 3.g ...
- bzoj1222: [HNOI2001]产品加工
注意时间都是 <= 5的.. #include<cstdio> #include<cstring> #include<cstdlib> #include< ...
- spring security +spring boot 自定义 403 页面
用的spring security 做的权限控制, 当 访问没有权限, 跳转 会跳到默认403 页面.不符合当前项目需求. 一下是解决方式: package com.ycmedia; import ...