小男孩‘自慰网亚洲一区二区,亚洲一级在线播放毛片,亚洲中文字幕av每天更新,黄aⅴ永久免费无码,91成人午夜在线精品,色网站免费在线观看,亚洲欧洲wwwww在线观看

分享

在C#中調(diào)用Excel

 醉人說夢 2014-07-24

1. 調(diào)用Excel的COM組件。
    在項目中打開Add Reference對話框,選擇COM欄,之后在COM列表中找到"Microsoft Excel 11.0 Object Library"(Office 2003),然后將其加入到項目的References中即可。Visual C#.NET會自動產(chǎn)生相應(yīng)的.NET組件文件,以后即可正常使用。

 

 

2. 打開Excel表格
    Excel.Application excel = new Excel.Application(); //引用Excel對象
    Excel.Workbook book = excel.Application.Workbooks.Add(Missing.Value); //引用Excel工作簿
    excel.Visible = bVisible; //使Excel可視

有時調(diào)用excel.Application.Workbooks.Add(Missing.Value)會遇到如下錯誤:
    Exception:
        Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))
這是Excel自身的一個bug,當(dāng)本地系統(tǒng)環(huán)境被設(shè)置成非英文的,而Excel是英文的時候,就會出現(xiàn),需要臨時設(shè)定英文環(huán)境,代碼如下:
    System.Globalization.CultureInfo CurrentCI = System.Threading.Thread.CurrentThread.CurrentCulture;
    System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");

 

 

3. 往Excel表格中插入數(shù)據(jù)
    Excel.Worksheet sheet = (Excel.Worksheet)book.Worksheets["Sheet1"]; // 選中當(dāng)前新建Sheet(一般為Sheet1)
有兩種插入方法
a. 逐格插入數(shù)據(jù)
    sheet.Cells[iRow, iCol] = value; // 左上角第一格的坐標(biāo)是[1, 1]
b. 按塊插入數(shù)據(jù)
    object[,] objVal = new object[Height, Length];
    // 設(shè)置數(shù)據(jù)塊
    Excel.Range range = sheet.get_Range(sheet.Cells[iRow, iCol], sheet.Cells[iRow + Height, iCol + Length])
    range.Value2 = objVal;

 

 

 

4. 清理內(nèi)存和恢復(fù)環(huán)境

    System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
    System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
    while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excel) > 0) ;
    range = null;
    sheet = null;
    book = null;
    excel = null;
    GC.Collect();
    System.Threading.Thread.CurrentThread.CurrentCulture = CurrentCI;

 

 

------------------------

 

特別是第二點。好有用!

 

 

 

 

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多