MyXls導出Excel的各種設置


MyXls是一個操作Excel的開源類庫,支持設置字體、列寬、行高(由BOSSMA實現)、合並單元格、邊框、背景顏色、數據類型、自動換行、對齊方式等,通過眾多項目的使用表現,證明MyXls對於創建簡單格式的Excel文件十分快捷方便。

本文將通過實例的方式詳細說明如何通過各種屬性設置MyXls的樣式,並附帶示例程序的源代碼。

 

// 准備測試數據
List<PersonInfo> list = new List<PersonInfo>();
for (int i = 1; i <= 200; i++)
{
    PersonInfo person = new PersonInfo()
    {
        RealName = "" + i,
        Gender = (i % 2 == 0 ? "" : ""),
        Age = 20 + (i % 3)
    };

    list.Add(person);
}

int recordCount = 200; // 要導出的記錄總數
int maxRecordCount = 100; // 每個sheet表的最大記錄數
int sheetCount = 1; // Sheet表的數目

XlsDocument xls = new XlsDocument();
xls.FileName = "MyXls-" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls";

// 計算需要多少個sheet表顯示數據
if (recordCount > maxRecordCount)
{
    sheetCount = (int)Math.Ceiling((decimal)recordCount / (decimal)maxRecordCount);
}

// Sheet標題樣式
XF titleXF = xls.NewXF(); // 為xls生成一個XF實例,XF是單元格格式對象
titleXF.HorizontalAlignment = HorizontalAlignments.Centered; // 設定文字居中
titleXF.VerticalAlignment = VerticalAlignments.Centered; // 垂直居中
titleXF.UseBorder = true; // 使用邊框 
titleXF.TopLineStyle = 1; // 上邊框樣式
titleXF.TopLineColor = Colors.Black; // 上邊框顏色
titleXF.LeftLineStyle = 1; // 左邊框樣式
titleXF.LeftLineColor = Colors.Black; // 左邊框顏色
titleXF.RightLineStyle = 1; // 右邊框樣式
titleXF.RightLineColor = Colors.Black; // 右邊框顏色
titleXF.Font.FontName = "宋體"; // 字體
titleXF.Font.Bold = true; // 是否加楚
titleXF.Font.Height = 12 * 20; // 字大小(字體大小是以 1/20 point 為單位的)

// 列標題樣式
XF columnTitleXF = xls.NewXF(); // 為xls生成一個XF實例,XF是單元格格式對象
columnTitleXF.HorizontalAlignment = HorizontalAlignments.Centered; // 設定文字居中
columnTitleXF.VerticalAlignment = VerticalAlignments.Centered; // 垂直居中
columnTitleXF.UseBorder = true; // 使用邊框 
columnTitleXF.TopLineStyle = 1; // 上邊框樣式
columnTitleXF.TopLineColor = Colors.Black; // 上邊框顏色
columnTitleXF.BottomLineStyle = 1; // 下邊框樣式
columnTitleXF.BottomLineColor = Colors.Black; // 下邊框顏色
columnTitleXF.LeftLineStyle = 1; // 左邊框樣式
columnTitleXF.LeftLineColor = Colors.Black; // 左邊框顏色
columnTitleXF.Pattern = 1; // 單元格填充風格。如果設定為0,則是純色填充(無色),1代表沒有間隙的實色 
columnTitleXF.PatternBackgroundColor = Colors.Red; // 填充的底色 
columnTitleXF.PatternColor = Colors.Default2F; // 填充背景色

// 數據單元格樣式
XF dataXF = xls.NewXF(); // 為xls生成一個XF實例,XF是單元格格式對象
dataXF.HorizontalAlignment = HorizontalAlignments.Centered; // 設定文字居中
dataXF.VerticalAlignment = VerticalAlignments.Centered; // 垂直居中
dataXF.UseBorder = true; // 使用邊框 
dataXF.LeftLineStyle = 1; // 左邊框樣式
dataXF.LeftLineColor = Colors.Black; // 左邊框顏色
dataXF.BottomLineStyle = 1;  // 下邊框樣式
dataXF.BottomLineColor = Colors.Black;  // 下邊框顏色
dataXF.Font.FontName = "宋體";
dataXF.Font.Height = 9 * 20; // 設定字大小(字體大小是以 1/20 point 為單位的)
dataXF.UseProtection = false; // 默認的就是受保護的,導出后需要啟用編輯才可修改
dataXF.TextWrapRight = true; // 自動換行

// 遍歷創建Sheet
for (int i = 1; i <= sheetCount; i++)
{
    // 根據計算出來的Sheet數量,一個個創建
    // 行和列的設置需要添加到指定的Sheet中,且每個設置對象不能重用(因為可以設置起始和終止行或列,就沒有太大必要重用了,這應是一個策略問題)
    Worksheet sheet;
    if (sheetCount == 1)
    {
        sheet = xls.Workbook.Worksheets.Add("人員信息表");
    }
    else
    {
        sheet = xls.Workbook.Worksheets.Add("人員信息表 - " + i);
    }

    // 序號列設置
    ColumnInfo col0 = new ColumnInfo(xls, sheet); // 列對象 
    col0.ColumnIndexStart = 0; // 起始列為第1列,索引從0開始
    col0.ColumnIndexEnd = 0; // 終止列為第1列,索引從0開始
    col0.Width = 8 * 256; // 列的寬度計量單位為 1/256 字符寬
    sheet.AddColumnInfo(col0); // 把格式附加到sheet頁上

    // 姓名列設置
    ColumnInfo col1 = new ColumnInfo(xls, sheet); // 列對象 
    col1.ColumnIndexStart = 1; // 起始列為第2列,索引從0開始
    col1.ColumnIndexEnd = 1; // 終止列為第2列,索引從0開始
    col1.Width = 16 * 256; // 列的寬度計量單位為 1/256 字符寬
    sheet.AddColumnInfo(col1); // 把格式附加到sheet頁上

    // 性別列設置
    ColumnInfo col2 = new ColumnInfo(xls, sheet); // 列對象 
    col2.ColumnIndexStart = 2; // 起始列為第3列,索引從0開始
    col2.ColumnIndexEnd = 2; // 終止列為第3列,索引從0開始
    col2.Width = 16 * 256; // 列的寬度計量單位為 1/256 字符寬
    sheet.AddColumnInfo(col2); // 把格式附加到sheet頁上

    // 年齡列設置
    ColumnInfo col3 = new ColumnInfo(xls, sheet); // 列對象 
    col3.ColumnIndexStart = 3; // 起始列為第4列,索引從0開始
    col3.ColumnIndexEnd = 3; // 終止列為第4列,索引從0開始
    col3.Width = 16 * 256; // 列的寬度計量單位為 1/256 字符寬
    sheet.AddColumnInfo(col3); // 把格式附加到sheet頁上

    // 行設置
    RowInfo rol1 = new RowInfo(); // 行對象
    rol1.RowHeight = 16 * 20; // 行高
    rol1.RowIndexStart = 3; // 行設置起始列,索引從1開始
    rol1.RowIndexEnd = (ushort)(maxRecordCount + 2); //行設置結束列
    sheet.AddRowInfo(rol1); // 把設置附加到sheet頁上

    // 合並單元格
    //sheet.Cells.Merge(1, 1, 1, 4);
    MergeArea titleArea = new MergeArea(1, 1, 1, 4); // 一個合並單元格實例(合並第1行、第1列 到 第1行、第4列) 
    sheet.AddMergeArea(titleArea); //填加合並單元格 

    // 開始填充數據到單元格
    Cells cells = sheet.Cells;

    // Sheet標題行,行和列的索引都是從1開始的
    Cell cell = cells.Add(1, 1, "人員信息統計表", titleXF);
    cells.Add(1, 2, "", titleXF); // 合並單元格后仍需要設置每一個單元格,樣式才有效
    cells.Add(1, 3, "", titleXF); // 合並單元格后仍需要設置每一個單元格,樣式才有效
    cells.Add(1, 4, "", titleXF); // 合並單元格后仍需要設置每一個單元格,樣式才有效
    sheet.Rows[1].RowHeight = 40 * 20; // 對指定的行設置行高

    // 列標題行
    cells.Add(2, 1, "序號", columnTitleXF);
    cells.Add(2, 2, "姓名", columnTitleXF);
    cells.Add(2, 3, "性別", columnTitleXF);

    // 最右側的列需要右邊框,通過修改樣式columnTitleXF的方式,還可以通過設置單元格屬性的方式實現。
    columnTitleXF.RightLineStyle = 1;
    columnTitleXF.RightLineColor = Colors.Black;
    cells.Add(2, 4, "年齡", columnTitleXF);

    sheet.Rows[2].RowHeight = 18 * 20; // 對指定的行設置行高

    // 行索引
    int rowIndex = 3;

    for (int j = 0; j < maxRecordCount; j++)
    {
        // 當前記錄在數據集合中的索引
        int k = (i - 1) * maxRecordCount + j;

        // 如果達到sheet最大記錄數則跳出
        if (k >= recordCount)
        {
            break;
        }

        // 設置單元格的值
        cells.Add(rowIndex, 1, k + 1, dataXF);
        cells.Add(rowIndex, 2, list[k].RealName, dataXF);
        cells.Add(rowIndex, 3, list[k].Gender, dataXF);

        // 最右側的列需要右邊框,通過給Cell設置屬性的方式實現,因為並不是所有的單元格都需要設置,不能通過修改樣式dataXF的方式
        Cell lastCell = cells.Add(rowIndex, 4, list[k].Age, dataXF);
        lastCell.RightLineStyle = 1;
        lastCell.RightLineColor = Colors.Black;

        // 行號遞增
        rowIndex++;
    }
}

// 在瀏覽器中輸出Excel文件
xls.Send();

 

1.創建一個Excel文檔:

XlsDocument xls = new XlsDocument();

2.創建一個WorkSheet:

Worksheet ws = xls.Workbook.Worksheets.Add("WorkSheet1");

3.指定列格式:

ColumnInfo colInfo = new ColumnInfo(xls, ws);
colInfo.ColumnIndexStart = ;
colInfo.ColumnIndexEnd = 17;
colInfo.Width = 15 * 256;
ws.AddColumnInfo(colInfo);

列格式必須每次都要重新定義,一個列格式不能重復使用。

4.指定單元格樣式:

XF xf = xls.NewXF();
xf.HorizontalAlignment = HorizontalAlignments.Centered;
xf.VerticalAlignment = VerticalAlignments.Centered;
xf.Pattern = 1;
xf.PatternColor = Colors.Default30;
xf.UseBorder = true;
xf.TopLineStyle = 1;
xf.TopLineColor = Colors.Black;
xf.BottomLineStyle = 1;
xf.BottomLineColor = Colors.Black;
xf.LeftLineStyle = 1;
xf.LeftLineColor = Colors.Black;
xf.RightLineStyle = 1;
xf.RightLineColor = Colors.Black;
xf.Font.Bold = true;
xf.Font.Height = 11 * 20;
xf.Font.ColorIndex = 1;

5.給單元格賦值:

ws.Cells.Add(2, 3, "金額(萬元)", xf);

6.合並單元格:

ws.Cells.Merge(1, 2, 2, 2);
//或者
ws.AddMergeArea(new MergeArea(1, 2, 1, 1));

7.MyXls合並單元格有個bug,就是合並后只是第一個單元格有樣式,其余的樣式丟失。所以寫了個函數來合並:

MergeRegion(ref ws, xf, "機構", 1, 1, 2, 1);

public void MergeRegion(ref Worksheet ws, XF xf, string title, int startRow, int startCol, intendRow, int endCol)
{
      for (int i = startCol; i <= endCol; i++)
       {
            for (int j = startRow; j <= endRow; j++)
             {
                 ws.Cells.Add(j, i, title, xf);
             }
       }
       ws.Cells.Merge(startRow, endRow, startCol, endCol);
}

雖然效率不怎么樣,但是對於出Excel報表,還OK。

8.指定單元格格式

cell.Format = StandardFormats.Decimal_1;

具體更多請參考源代碼的StandardFormats類。

9.保存或者發送Excel:

xls.Send();
//或者
xls.Save();

 

MyXls下載地址:(我下載的版本是0.63,很多地方下載的版本是0.51,老版本沒有單元格合並等功能)

http://sourceforge.net/projects/myxls/files/

 

 

本博客所有文章如無特別注明均為原創。
復制或轉載請以超鏈接形式注明轉自波斯馬,原文地址《MyXls導出Excel的各種設置


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM