2016/06/15

C#.Net 讀取行列資料

程式碼:
class Ex{
    private EXCEL.Application _app;
    private EXCEL.Worksheet _sheet;
    private EXCEL.Workbook _workbook;
    private int _rowCount = 5;
    private int _columnCount = 5;
     
    public Ex(String fileName){
        //調用EXCEL
        this._app = new EXCEL.Application();
 
        //隱藏EXCEL
        this._app.Visible = false;
 
        //開啟檔案
        this._workbook = this._app.Workbooks.Open(fileName, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing, Type.Missing, 
        Type.Missing, Type.Missing, Type.Missing);
        this._sheet = (EXCEL.Worksheet)_workbook.Worksheets[1];
    }
     
    public void Show(){
        var cells = this._sheet.Cells;

        for (int r = 1; r <= _rowCount; r++) {
            for (int c = 1; c <= _columnCount; c++){
                //初始行列為1
                var content = (Object)(cells[r, c] as EXCEL.Range).Value;
                if (content != null)
                    if (String.IsNullOrEmpty(content.ToString()) != true)
                        Console.WriteLine(content);
                }
            }
    }
}