程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C#/.NET 4.0新特性生成Excel文檔

C#/.NET 4.0新特性生成Excel文檔

編輯:C#入門知識

直接上代碼:

using MSExcel = Microsoft.Office.Interop.Excel;
public class ExcelHelper
{
    /// <summary>
    /// Creates the excel file by column.
    /// </summary>
    /// <param name="filename">The filename.</param>
    /// <param name="columns">The columns.</param>
    public static void CreateExcelFileByColumn (string filename, IEnumerable<ColumnData> columns)
    {
        createExcelFile (filename, excelApp =>
        {
            //Write data into the workbook by column.
            int columnIndex = 1;
            foreach (var column in columns)
            {
                //Write the header.
                excelApp.Cells[1, columnIndex].Value = column.Header;

                //Write the following lines in this column.
                int rowIndex = 2;
                foreach (var cell in column.Data)
                {
                    excelApp.Cells[rowIndex++, columnIndex].Value = cell;
                }
                columnIndex++;
            }
        });
    }

    /// <summary>
    /// Creates the excel file by row.
    /// </summary>
    /// <param name="filename">The filename.</param>
    /// <param name="rows">The rows.</param>
    public static void CreateExcelFileByRow (string filename, IEnumerable<IEnumerable> rows)
    {
        createExcelFile (filename, excelApp =>
        {
            //Write data into the workbook by row.
            int rowIndex = 1;
            foreach (var row in rows)
            {
                int columnIndex = 1;
                foreach (var cell in row)
                {
                    excelApp.Cells[rowIndex, columnIndex++].Value = cell;
                }
                rowIndex++;
            }
        });
    }

    /// <summary>
    /// Creates the excel file and perform the specified action.
    /// </summary>
    /// <param name="filename">The filename.</param>
    /// <param name="action">The action.</param>
    private static void createExcelFile (string filename, Action<MSExcel.Application> action)
    {
        //Create the excel application and set it to run in background.
        var excelApp = new MSExcel.Application ();
        excelApp.Visible = false;

        //Add a new workbook.
        excelApp.Workbooks.Add ();

        //Perform the action.
        action (excelApp);

        //Save the workbook then close the file.
        excelApp.ActiveWorkbook.SaveAs (Filename: filename, 
            FileFormat: MSExcel.XlFileFormat.xlWorkbookNormal);
        excelApp.ActiveWorkbook.Close ();

        //Exit the excel application.
        excelApp.Quit ();
    }
}

 

這個類提供了兩個方法:按列數據創建excel文件和按行數據創建excel文件。

注意此時excelApp.Cells[row,column]的返回值已經是.NET 4.0中引入的dynamic類型,
而不再是原來的object類型,所以可以直接在上面調用.Value()方法,由DLR動態解析;
而在以前,必須首先強轉其返回值為Range,寫成:

((MSExcel.Range)excelApp.Cells[row, column]).Value2 = value;

此外,由於C# 4.0中命名參數和可選參數的引入,也使得對COM對象的方法調用變得相當
簡潔,僅看最後的SaveAs方法,以前必須傳遞一堆Type.Missing對象以表示不傳遞此參
數或使用默認值,如:

excelApp.ActiveWorkbook.SaveAs (filename,
    MSExcel.XlFileFormat.xlWorkbookNormal,
    Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, MSExcel.XlSaveAsAccessMode.xlNoChange,
    Type.Missing, Type.Missing, Type.Missing,
    Type.Missing, Type.Missing); 

 

非常頭痛,現在只需用命名參數指定要給出的參數,其他的由於是可選參數,都會自動
給默認值:

excelApp.ActiveWorkbook.SaveAs (Filename: filename,
    FileFormat: MSExcel.XlFileFormat.xlWorkbookNormal);

 

意思非常清晰。

最後補上那個簡單類ColumnData的定義:

/// <summary>
/// Represents the header and data of a column.
/// </summary>
public class ColumnData
{
    /// <summary>
    /// Gets or sets the header.
    /// </summary>
    /// <value>The header.</value>
    public string Header { get; set; }

    /// <summary>
    /// Gets or sets the data.
    /// </summary>
    /// <value>The data.						

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved