MyXls组件操作Excel报表(C#)

    在后台调用excel组件,生成Excel,虽然可以Excel文件进行完全控制,可以生成任何复杂的格式,但是有个很大的缺点,这种方式会产生很多Excel进程很难完全清掉,特别是在出错的时候,可能会使整个服务器崩溃。本文为大家介绍一个C#写的开源组件,并简单说下office2003和以上版本支持的XML格式。

 操作Excel二进制格式

    OpenOffice.org发布过的俩个文档Excel File Format (BIFF8)SpecificationMicrosoft CompoundDocument (OLE2) Format SpecificationExcel的二进制格式做了一个比较详细的说明,依靠这些信息,我们可以直接操作Office二进制格式文档。

  MyXls是一个C#写的开源组件,可以用来生成具有很多表格且包含格式的Excel文件。它提供了一套基于对象的API,非常容易使用。

MyXls这个组件的DLL 和代码 可以在这下载到:
http://sourceforge.net/project/showfiles.php?group_id=205384&package_id=245371
以下是一个事例子。。

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using org.in2bits.MyXls;

namespace WebApplication1
{
    
public partial class _Default : System.Web.UI.Page
    {
        
protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        
protected void Button1_Click(object sender, EventArgs e)
        {
            XlsDocument xls 
= new XlsDocument();

            Worksheet sheet 
= xls.Workbook.Worksheets.Add("sheet");//状态栏标题名称
            Cells cells = sheet.Cells;

            cells.Add(
11"Name");
            cells.Add(
12"Age");
            cells.Add(
13"Email");
            cells.Add(
14"Description");

            
for (int i = 0; i < 5000; i++)
            {
                cells.Add(i 
+ 21"netflu");
                cells.Add(i 
+ 2228.ToString());
                cells.Add(i 
+ 23"xxx@163.com");
                cells.Add(i 
+ 24"sheet.Cells.AddValueCell(rowIndex, colIndex, row[col.ColumnName].ToString());//将数据添加到xls表格里");
            }

            
//foreach (DataRow row in table.Rows)
            
//{
            
//    rowIndex++;
            
//    colIndex = 0;
            
//    foreach (DataColumn col in table.Columns)
            
//    {
            
//        colIndex++;
            
//        //sheet.Cells.AddValueCell(rowIndex, colIndex, row[col.ColumnName].ToString());//将数据添加到xls表格里
            
//        Cell cell = cells.AddValueCell(rowIndex, colIndex, Convert.ToDouble(row[col.ColumnName].ToString()));//转换为数字型
            
//        //如果你数据库里的数据都是数字的话 最好转换一下,不然导入到Excel里是以字符串形式显示。
            
//        cell.Font.FontFamily = FontFamilies.Roman; //字体
            
//        cell.Font.Bold = true;  //字体为粗体            
            
//    }
            
//}
            xls.Send();
        }

    }
}

 

 

posted @ 2010-02-12 15:22  蛤蟆  阅读(1405)  评论(0)    收藏  举报