C# API: 產生和讀取Excel檔案

來源:互聯網
上載者:User

標籤:datagridview   style   class   code   java   http   

我們想為使用者提供一些資料,考慮再三, 大家認為對於使用者(人,而非機器)的可讀性, Excel檔案要好一些.

因為相比csv,xml等檔案, Excel中我們可以運用自動篩選, 視窗鎖定, 還可以控制背景顏色, 前景顏色, 字型, 網格等等...

商務邏輯並不複雜, 檔案的內容和格式也比較固定,所以大家決定直接拿C#去建立這些檔案.

 

於是一搜尋,首先來到了這個連結:C# Excel Tutorial

裡麵包含了下面這些主題的程式碼範例, 樣本很詳細, 編譯可直接運行.

  • How to create Excel file in C#
  • How to open an Excel file in C#
  • How to read an Excel file in CSharp
  • How to format an Excel file using C#
  • How to insert a picture in excel from C# App
  • How to insert a background picture in excel
  • How to create Excel Chart from C#
  • How to export excel chart from C#
  • How to excel chart in C# picturebox
  • C# data validation input box in excel file
  • How to read from an Excel file using OLEDB
  • How to insert data to Excel file using OLEDB
  • How to update data in Excel file using OLEDB
  • How to export databse to excel file
  • How to export DataGridView to excel file

 

為了理解上面這些代碼需要理解一下Excel的物件模型, 可以參考msdn的下面這個連結

Excel Object Model Overview

 

裡面介紹了4個核心對象:

  • Microsoft.Office.Interop.Excel.Application

  • Microsoft.Office.Interop.Excel.Workbook

  • Microsoft.Office.Interop.Excel.Worksheet

  • Microsoft.Office.Interop.Excel.Range

前三個對象比較好理解, 關鍵在於第四個對象:Range.

起初我以為更改一些儲存格的字型顏色格式等等的, 是需要通過Cell這個對象來做.

看完了之後才發現, 這些操作其實都是通過Range來完成的.

還包括和並儲存格, 設定網格線等等, 甚至讀取和設定一個儲存格的值,都可以通過Range來完成,

所以基本上當我們操作excel的時候, 我們最經常的就是和Range對象打交道, 而很少使用Cell等對象.

如果有什麼需求不知道怎麼實現,

建議可以先到Range對象裡面翻一翻, 看看msdn上Range對象的Members,Methods,Properties的相關文檔.

 

還有一點要補充的是:

不僅僅是C#, 還包括其他語言的Excel API, 都是對Excel物件模型的直接類比和封裝.不過Java,Ruby等等.

也就是說, 其他語言的Excel API也都會有上面那四個主要對象, 而且也都會以近乎相同的方式, 乾著差不多的事兒.

 

 

接下來想寫一寫關於Missing.Value的事兒

對於前面給出的,建立Excel表的例子的代碼, 轉載如下:

這段代碼中,很多函數調用都傳遞了這個參數:

object misValue = System.Reflection.Missing.Value;

他的詳細介紹參考這個連結Missing Class 上面的例子,

簡單的說就是:

當我想以一些參數的預設值來調用一些dll中的方法的, 我們在方法調用中忽略掉這些參數也不對,

我們用null傳遞給這些參數還不對,

這時我們便可以給這些參數賦值以Missing.Value來告訴運行時環境, 用這個參數的預設值幫我運行吧.

 

對於這段代碼還有一個需要注意的問題:

注意Application,Workbook,Worksheet這三個對象的清理工作

該儲存的儲存, 該close的close, 該quit的quit, 最後, 他們還都應該被release

 

C#代碼  
  1. using System;  
  2. using System.Windows.Forms;  
  3. using Excel = Microsoft.Office.Interop.Excel;   
  4.   
  5. namespace WindowsApplication1  
  6. {  
  7.     public partial class Form1 : Form  
  8.     {  
  9.         public Form1()  
  10.         {  
  11.             InitializeComponent();  
  12.         }  
  13.   
  14.         private void button1_Click(object sender, EventArgs e)  
  15.         {  
  16.             Excel.Application xlApp ;  
  17.             Excel.Workbook xlWorkBook ;  
  18.             Excel.Worksheet xlWorkSheet ;  
  19.             object misValue = System.Reflection.Missing.Value;  
  20.   
  21.             xlApp = new Excel.ApplicationClass();  
  22.             xlWorkBook = xlApp.Workbooks.Add(misValue);  
  23.   
  24.             xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);  
  25.             xlWorkSheet.Cells[1, 1] = "http://csharp.net-informations.com";  
  26.   
  27.             xlWorkBook.SaveAs("csharp-Excel.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);  
  28.             xlWorkBook.Close(true, misValue, misValue);  
  29.             xlApp.Quit();  
  30.   
  31.             releaseObject(xlWorkSheet);  
  32.             releaseObject(xlWorkBook);  
  33.             releaseObject(xlApp);  
  34.   
  35.             MessageBox.Show("Excel file created , you can find the file c:\\csharp-Excel.xls");  
  36.         }  
  37.   
  38.         private void releaseObject(object obj)  
  39.         {  
  40.             try  
  41.             {  
  42.                 System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);  
  43.                 obj = null;  
  44.             }  
  45.             catch (Exception ex)  
  46.             {  
  47.                 obj = null;  
  48.                 MessageBox.Show("Exception Occured while releasing object " + ex.ToString());  
  49.             }  
  50.             finally  
  51.             {  
  52.                 GC.Collect();  
  53.             }  
  54.         }  
  55.     }  
  56. }  

 

 

 

最後想寫一下關於如何設定字型的顏色, 以及儲存格的背景顏色的事兒.

以背景色設定為紅色為例, 首先我們可以寫出形如下面這樣的代碼:

 

C#代碼  
  1. Excel.Range chartRange;  
  2. chartRange = xlWorkSheet.get_Range("a1", "e4");  
  3. chartRange.Interior.Color = 255;  

 

但是這個255很不好記, 比如青色對應的數字是16777164, 這個就更加不好理解.

所以我們可以改為這樣設定顏色, 使用ColorTranslator轉換一下:

C#代碼  
  1. chartRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);  

 

最後還有一種設定方法是不對Color進行設定, 而是設定相應的ColorIndex, 形如下面這樣:

C#代碼  
  1. chartRange.Interior.ColorIndex = 3;  

 

ColorIndex的色表參考下面這兩個串連:

Color Palette and the 56 Excel ColorIndex Colors

Excel Color Palette and Color Index change using VBA

第一個串連特別詳細,

第二個串連則介紹了如何使用VBA在Excel檔案中產生這些色表, 同時還提供了一個xls格式的色表檔案下載.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.