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导出简易组件的更多相关文章

  1. 6、jeecg 笔记之 自定义excel 模板导出(一)

    1.前言 jeecg 中已经自带 excel 的导出导出功能,其所使用的是 easypoi,尽管所导出的 excel 能满足大部分需求, 但总是有需要用到自定义 excel 导出模板,下文所用到的皆是 ...

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

    在DCOM 中不存在WORD.EXCEL等OFFICE组件   最近在做一个关于office转存PDF的Web项目.开发过程一切顺利. 起初在网上找到一些Word,PPT转PDF的代码.很好用.一切顺 ...

  3. java使用poi自定义excel标题头并导出(springmvc+poi)

    项目使用的是jeecg开源框架(springmvc+spring+hibernate+......等)此代码仅供参考!如有更好的意见或建议可留言. 1 controller 层 /** * excel ...

  4. 并发编程概述 委托(delegate) 事件(event) .net core 2.0 event bus 一个简单的基于内存事件总线实现 .net core 基于NPOI 的excel导出类,支持自定义导出哪些字段 基于Ace Admin 的菜单栏实现 第五节:SignalR大杂烩(与MVC融合、全局的几个配置、跨域的应用、C/S程序充当Client和Server)

    并发编程概述   前言 说实话,在我软件开发的头两年几乎不考虑并发编程,请求与响应把业务逻辑尽快完成一个星期的任务能两天完成绝不拖三天(剩下时间各种浪),根本不会考虑性能问题(能接受范围内).但随着工 ...

  5. 自定义分页Gridview中Excel导出

    先上图,如图所示导出所有查询出的数据 用的是AspNetPager分页控件,这个导出方法,不受分页和gridview列中数据的约束,可以导出您想导出的数据 首先前台页面代码,lblink即为导出exc ...

  6. asp.net(C#) Excel导出类 导出.xls文件

    ---恢复内容开始--- using Microsoft.Office.Interop.Excel; 针对office 2003需添加引用Microsoft   Excel   11.0   Obje ...

  7. 也谈Excel导出

    吐槽 Excel导出在天朝的软件大环境下,差点成为软件开发必备.俺就遇到过,所有报表不提供导出功能,就能不验收的囧事.报表能查看能打印能形成图表已经完美,实在搞不懂导出excel有个毛用,但是公司依靠 ...

  8. Asp.Net 常用工具类之Office—Excel导出(4)

    开发过程中各类报表导入导出防不胜防,网上也是各种解决方法层出不穷,比如Excel,CSV,Word,PDF,HTML等等... 网上各种导出插件也是层出不穷,NPOI,微软Microsoft.Offi ...

  9. C#Excel导出注意事项

    Excel 导出 1.首先在服务器中安装office ,并且要注册2.在组件服务中 设置Microsoft.excel.appliction 属性中设置自定义加network service用户并交互 ...

随机推荐

  1. 折腾iPhone的生活——越狱

    这次我也加入了越狱大军,也不是为的什么免费软件,只是遵从我玩机的本质,既然想要玩透这个机子,当然要所有都试过来,就果断越狱了,关于越狱的好处和坏处,我会在另外一篇博客里阐述,这篇博客主要就说怎么样进行 ...

  2. MongoDB基础知识 01

    MongoDB基础知识  1. 文档  文档是MongoDB中的数据的基本单元,类似于关系型数据库管理系统的行. 文档是键值对的一个有序集.通常包含一个或者多个键值对. 例如: {”greeting& ...

  3. Android实现弹出输入法时,顶部固定,中间部分上移的效果

    前言 最近做项目时碰到一个问题,在意见反馈里面,提交按钮写到顶部,当用户输入反馈意见或者邮箱手机号时,弹出的输入法会上移整个页面,导致提交按钮显示不了. 很明显,这样的界面是非常不友好的,找了一些资料 ...

  4. Redis学习记录之Java中的初步使用

    1.关于Redis redis下载地址:<span style="font-family: Arial, Helvetica, sans-serif;">http:// ...

  5. java.lang.ClassCastException: Ljava.lang.Object; cannot be cast to com.entity.Advertisem异常

    今天一不小心就碰到了这样的问题,以前从来没有碰到过,在网上搜了很多办法,思路正确,但是还是要根据自己的程序改变. 一开始写的是hql语句进行统计每个月的数据,但是试了很久,程序一直提醒hql语句异常, ...

  6. EnterpriseArchitectect 软件的勾选的几个选项对应的中文意思

    Business Process 业务流程 Requirements 需求分析 Use Case 用例 Domain Model 领域模型 Class 类 Database 数据库设计 Compone ...

  7. OpenCV 最小二乘拟合方法求取直线倾角

    工业相机拍摄的图像中,由于摄像质量的限制,图像中的直线经过处理后,会表现出比较严重的锯齿.在这种情况下求取直线的倾角(其实就是直线的斜率),如果是直接选取直线的开始点和结束点来计算,或是用opencv ...

  8. 树莓派入手(烧写系统,调整分区,配置Java环境,串口GPS配置) 分类: Raspberry Pi 2015-04-09 21:13 145人阅读 评论(0) 收藏

    原来的tf卡无故启动不起来,检查发现其文件系统分区使用率为0%. 数据全部丢失!!!!! 血的教训告诉我们备份文件系统的重要性,一切需要重头来.... 烧录系统 安装系统有两种方式, NOOBS工具安 ...

  9. Android 图标上面添加提醒(二)使用开源UI类库 Viewbadger

    版权声明:本文为博主原创文章,未经博主允许不得转载. 上一篇讲到用canvas进行绘制得到对应最终的bitmap. 在实际应用中,我们除了给图标添加数字外,也有可能加一些红色方块之类的图标作为新功能的 ...

  10. MySQL 的 read_buffer_size 参数是如何影响写缓冲和写性能的?

    Each thread // that does a sequential scan . The value of this variable should be a multiple of 4KB. ...