您的位置:首页 > 其它

.NET -Myxls组件 导入导出Excel 服务器不需要安装Excel [魏言整理]

2009-06-13 10:04 597 查看
using System;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.IO;
using org.in2bits.MyXls;//首先导入命名空间
public partial class _Default : System.Web.UI.Page
{
/// <summary>
/// 使用myxls.dll组件操作Excle 服务器不需要装office
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{

}
}
protected void Button1_Click(object sender, EventArgs e)
{
//生成Excel开始

XlsDocument xls = new XlsDocument();//创建空xls文档

xls.FileName = Server.MapPath("~/Demo.xls");//保存路径,如果直接发送到客户端的话只需要名称 生成名称

Worksheet sheet = xls.Workbook.Worksheets.AddNamed("Demo"); //创建一个工作页为Dome

//设置文档列属性
ColumnInfo cinfo = new ColumnInfo(xls, sheet);//设置xls文档的指定工作页的列属性
cinfo.Collapsed = true;
//设置列的范围 如 0列-10列
cinfo.ColumnIndexStart = 0;//列开始
cinfo.ColumnIndexEnd = 10;//列结束
cinfo.Collapsed = true;
cinfo.Width = 90 * 60;//列宽度
sheet.AddColumnInfo(cinfo);
//设置文档列属性结束

//设置指定工作页跨行跨列
MergeArea ma = new MergeArea(1, 1, 1, 5);//从第1行跨到第二行,从第一列跨到第5列
sheet.AddMergeArea(ma);
//设置指定工作页跨行跨列结束

//创建列样式创建列时引用
XF cellXF = xls.NewXF();
cellXF.VerticalAlignment = VerticalAlignments.Centered;
cellXF.HorizontalAlignment = HorizontalAlignments.Centered;
cellXF.Font.Height = 24 * 12;
cellXF.Font.Bold = true;
cellXF.Pattern = 1;//设定单元格填充风格。如果设定为0,则是纯色填充
cellXF.PatternBackgroundColor = Colors.Red;//填充的背景底色
cellXF.PatternColor = Colors.Red;//设定填充线条的颜色
//创建列样式结束

//创建列
Cells cells = sheet.Cells; //获得指定工作页列集合
//列操作基本
Cell cell=cells.Add(1, 1, "Myxls组件测试程序 Dome",cellXF);//添加标题列返回一个列 参数:行 列 名称 样式对象
//设置XY居中
cell.HorizontalAlignment = HorizontalAlignments.Centered;
cell.VerticalAlignment = VerticalAlignments.Centered;
//设置字体
cell.Font.Bold = true;//设置粗体
cell.Font.ColorIndex = 0;//设置颜色码
cell.Font.FontFamily = FontFamilies.Roman;//设置字体 默认为宋体
//创建列结束

//创建列表头
Cell title=cells.Add(2,1,"ID");
title.HorizontalAlignment = HorizontalAlignments.Right;
title.VerticalAlignment = VerticalAlignments.Centered;

//创建模拟数据

for (int i = 0; i < 10;i++ )
{
cells.Add(i + 3, 1, i);//添加列,不设置列属性就不用返回列对象
}
//生成保存到服务器如果存在不会覆盖并且报异常所以先删除在保存新的
File.Delete(Server.MapPath("~/Demo.xls"));//删除
//保存文档
xls.Save();//保存到服务器
xls.Send();//发送到客户端

}
protected void Button2_Click(object sender, EventArgs e)
{
//导入Excel

//加载要导入的Excel
XlsDocument xls = new XlsDocument(Server.MapPath("~/Demo.xls"));//加载外部Excel
//获得Excel中的指定一个工作页
Worksheet sheet = xls.Workbook.Worksheets["Demo"];
//读取数据 循环每sheet工作页的每一行,不读取前两行
for (int i = 3; i < sheet.Rows.Count; i++)
{
//sheet.Rows[ushort.Parse(i.ToString())].GetCell(1).Value
//解释:获得指定工作页行集合的指定行的指定列的值
Response.Write(sheet.Rows[ushort.Parse(i.ToString())].GetCell(1).Value);
Response.Write("<br/>");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: