现在的位置: 首页 > 综合 > 正文

(C#)用MyXls生成Excel报表

2013年12月02日 ⁄ 综合 ⁄ 共 5669字 ⁄ 字号 评论关闭

MyXls是用C#开源项目,可以应用于asp.net 或者 .net应用程序上。它根据微软公开的Excle文档格式文件(BIFF),以二进制格式直接生成excel文档,支持Excel versions 97 - 2007. 。这意味着可以不用在服务器上安装office就能够以excle格式输出数据库中存储的数据了。这对于许多项目来说都是很有用的。

     目前MyXls已经实现了单元格(cell)的格式设置,包括文本颜色、文本大小、字体、单位格边框、底色、列宽、行高,合并单元格,多个sheet页等功能。
     目前MyXls还不支持在excel文档中生成对象(如、文本框、按钮等)。MyXls主页称即将实现对excel文件的读取功能,个人认为读取的功能的用处还不是很多。

网址及下载:
http://myxls.in2bits.org/
----------------------------------------------------------------------------------------------------------------------------------------------
这是我测试的示例代码

private void button2_Click(object sender, EventArgs e)
        {
            xlsGridview(ds, "Data");//调用xlsGridview方法生成Excel报表
        }

private void xlsGridview(DataSet ds, string xlsName)
        {
            XlsDocument xls = new XlsDocument();
            xls.FileName = xlsName;

            int rowIndex = 1;
            int colIndex = 0;

            DataTable table = ds.Tables[0];
            Worksheet sheet = xls.Workbook.Worksheets.Add("Hello World Sheet");//状态栏标题名称
            Cells cells = sheet.Cells;
            foreach (DataColumn col in table.Columns)
            {
                colIndex++;
                //sheet.Cells.AddValueCell(1,colIndex,col.ColumnName);//添加XLS标题行
                cells.Add(1, colIndex, col.ColumnName);
            }

            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()));
//转换为数字型

                    Cell cell = cells.Add(rowIndex, colIndex, row[col.ColumnName].ToString());
                    //如果你数据库里的数据都是数字的话 最好转换一下,不然导入到Excel里是以字符串形式显示。
                    //cell.Font.FontFamily = FontFamilies.Roman; //字体
                    //cell.Font.Bold = true; //字体为粗体
                    cell.Font.Weight = FontWeight.Bold;
                }
            }
            xls.Save();
        }

----------------------------------------------------------------------------------------------------------------------------------------------
Overview
MyXLS is a .NET 2.0 library that writes and reads native Excel files quickly and easily, including formatting and multiple sheets. Generate Excel files for ASP.NET sites or .NET applications. Doesn't require Excel on the server or any licensing. Compatible
with Excelversions 97 and up. Features

    * Pure .NET code - no P/Invokes, Interop assemblies, or Excel COM automation behind the scenes.
    * No other dependencies - add and reference the MyXls dll in your project and go!
    * Fast! (we will be adding some performance metrics)
    * Lightweight! The dll is only ~100 KB
    * Free to use, no licensing restrictions.
    * Open Source Project
    * The files generated are 100% compatible with Excel versions 97 and up. Files are BIFF8, which is Excel 97-2003's native format, and fully forward compatible with Excel 2007.
    * Create any number of Worksheets
    * Name Worksheets
    * Write values to any cell on any Worksheet - values don't have to be in contiguous ranges
    * Supports a good portion of Excel's formatting capabilities (bold, underline, italic, rotation, etc)
    * Supports writing Metadata - values displayed in Excel's File->Properties dialog box

Configuring Your Project

MyXls is easy to add to your project.

  1. Download the binaries.
  2. Add a reference to org.in2bits.MyXls.dll in your project
  3. Add a using statement to reference the MyXls namespace using org.in2bits.MyXls;

Edit

Writing an Excel Document

Edit

Basic Example

This example creates a new
Excel
file, adds a named worksheet, and puts a value into a cell in that worksheet. Very basic but it shows how in six lines of code you can use MyXls to create

Excel
files.

XlsDocument doc = new XlsDocument(); doc.FileName = "HelloWorld.xls"; Worksheet sheet = doc.Workbook.Worksheets.Add("Hello World Sheet"); Cell cell = sheet.Cells.Add(1, 1, "Hello!"); cell.Font.Weight = FontWeight.Bold;

doc.Save();

Edit

Web Application Support

MyXls has built in support for web applications. Using the XlsDocument.Send() method you can easily send an

Excel
spreadsheet back to the client.

// Send the document back as an attachement // Same as doc.Send(XlsDocument.SendMethods.Attachment); doc.Send();

// or use // send the document back within the page doc.Send(XlsDocument.SendMethods.Inline);

Edit

Reading an Excel Document

Read support is still relatively experimental. However, MyXls should be able to read all values (even formulas! though you can't write formulas with it yet!) and formatting. It will not read any OLE objects, Pivot Tables, Charts/Graphs, VBA modules, etc. --
it will simply ignore them. It supports only Excel versions 97 thru 2003/XP - 2007's .xlsx XML format is not supported. However, you can try the below to see if it will work for you, and please

submit a bug
if you have any problems beyond that.

Edit

Basic Example

This example reads various values (including formula results) from an example Excel file,

BlankBudgetWorksheet.xls
. This does does not show retrieving formatting (font size, borders, etc.), but you should get the basic idea of how to reference the cells on which you would read those other properties:

XlsDocument xls = new XlsDocument(@"c:\Path\To\BlankBudgetWorksheet.xls", null); //read in the Excel file

string worksheet1Name = xls.Workbook.Worksheets0.Name; //Worksheet 1 name : "Budget" string worksheet2Name = xls.Workbook.Worksheets1.Name;
//Worksheet 2 name : "Income" string worksheet3Name = xls.Workbook.Worksheets2.Name; //Worksheet 3 name : "Expenses"

Worksheet sheet = xls.Workbook.Worksheets0; //get a reference to a Worksheet

string cellH6HyperlinkText = (string)sheet.Rows6.CellAtCol(8).Value; //Cell H6 hyperlink text : "See reverse for instructions and guidelines" string cellJ7Value = (string)sheet.Rows7.CellAtCol(10).Value;
//Cell J7 value : "Budget Plan" string cellG28Value = (string)sheet.Rows28.CellAtCol(7).Value; //Cell G28 value : "Administrative Support (12% of Revenue)" long cellC10Value
= (long)sheet.Rows10.CellAtCol(3).Value; //Cell C10 value : 6801 string cellF10FormulaResultValue = (string)sheet.Rows10.CellAtCol(6).Value;
//Cell F10 Formula result value : "- 20"

抱歉!评论已关闭.