c#如何生成Excel(.xls和.xlsx)文件


在工作中經常遇到需要用c#生成Excel文件(.xls和.xlsx格式),完全免費開源的ExcelLibrary是一個不錯的選擇。

ExcelLibrary項目的地址爲:

https://code.google.com/p/excellibrary/

ExcelLibrary源碼下載地址:  

https://code.google.com/p/excellibrary/downloads/list

  ExcelLibrary提供了一個基於本地.NET應用程序的解決方案,可以用來新建,讀取和修改Excel文件而不需要使用COM或者OLEDB。現在已經支持.xls文件格式,.xlsx(Excel 2007)也即將被支持。

ExcelLibrary官方示例代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//create new xls file
string file = "C:\\newdoc.xls";
Workbook workbook = new Workbook();
Worksheet worksheet = new Worksheet("First Sheet");
worksheet.Cells[0, 1] = new Cell((short)1);
worksheet.Cells[2, 0] = new Cell(9999999);
worksheet.Cells[3, 3] = new Cell((decimal)3.45);
worksheet.Cells[2, 2] = new Cell("Text string");
worksheet.Cells[2, 4] = new Cell("Second string");
worksheet.Cells[4, 0] = new Cell(32764.5, "#,##0.00");
worksheet.Cells[5, 1] = new Cell(DateTime.Now, @"YYYY\-MM\-DD");
worksheet.Cells.ColumnWidth[0, 1] = 3000;
workbook.Worksheets.Add(worksheet);
workbook.Save(file);
// open xls file
Workbook book = Workbook.Load(file);
Worksheet sheet = book.Worksheets[0];
 // traverse cells
 foreach (Pair<Pair<intint>, Cell> cell in sheet.Cells)
 {
     dgvCells[cell.Left.Right, cell.Left.Left].Value = cell.Right.Value;
 }
 // traverse rows by Index
 for (int rowIndex = sheet.Cells.FirstRowIndex;
rowIndex <= sheet.Cells.LastRowIndex; rowIndex++)
 {
     Row row = sheet.Cells.GetRow(rowIndex);
     for (int colIndex = row.FirstColIndex;
colIndex <= row.LastColIndex; colIndex++)
     {
         Cell cell = row.GetCell(colIndex);
     }
 }


ExcelLibrary示例代碼二(從數據庫中獲取數據然後創建Excel文件):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Create the data set and table
DataSet ds = new DataSet("New_DataSet");
DataTable dt = new DataTable("New_DataTable");
//Set the locale for each
ds.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
dt.Locale = System.Threading.Thread.CurrentThread.CurrentCulture;
//Open a DB connection (in this example with OleDB)
OleDbConnection con = new OleDbConnection(dbConnectionString);
con.Open();
//Create a query and fill the data table with the data from the DB
string sql = "SELECT Whatever FROM MyDBTable;";
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adptr = new OleDbDataAdapter();
adptr.SelectCommand = cmd;
adptr.Fill(dt);
con.Close();
//Add the table to the data set
ds.Tables.Add(dt);
//Here's the easy part. Create the Excel worksheet from the data set
ExcelLibrary.DataSetHelper.CreateWorkbook("MyExcelFile.xls", ds);


另外,還可以使用EPPlus, EPPlus支持生成Excel 2007/2010 格式的文件(.xlsx) 其主頁爲:

http://epplus.codeplex.com/

EPPlus項目基於LGPL開源協議。

文章轉載自:[169it科技資訊]
本文標題:c#如何生成Excel(.xls和.xlsx)文件

發佈了0 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章