c# Excel的基本操作

來源:互聯網
上載者:User

本文的主要內容:c#實現對Excel的Open、Save、合併儲存格、儲存格賦值的操作。

ExcelHelper代碼:

 1 class ExcelHelper
2 {
3 publicstaticvoid SaveData()
4 {
5 string filePath = Environment.CurrentDirectory +"\\Data";
6 if (!Directory.Exists(filePath))
7 {
8 Directory.CreateDirectory(filePath);
9 }
10 string fileName =string.Format("{0}\\{1}.xls", filePath, DateTime.Now.ToShortDateString());
11
12 Excel.Application excelApp =new Excel.ApplicationClass();
13 //建立活頁簿
14 if(!File.Exists(fileName))
15 {
16 Excel.Workbook workBookNew = excelApp.Workbooks.Add(true);
17 //建立工作表
18 Excel.Worksheet worksheetNew = workBookNew.ActiveSheet as Excel.Worksheet;
19 workBookNew.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, true, false, Missing.Value);
20 }
21 Excel.Workbook workBook = excelApp.Workbooks.Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, false, Missing.Value, Missing.Value, true, false, Missing.Value, false, false, false);
22
23 //建立工作表
24 Excel.Worksheet worksheet = workBook.ActiveSheet as Excel.Worksheet;
25
26 Excel.Range r = worksheet.get_Range(
27 worksheet.Cells[1, 1], worksheet.Cells[3, 3]); //選取儲存格
28 r.MergeCells =true;
29
30 r.Value2 ="我愛中華"; //設定儲存格內文本
31 r.Font.Name ="黑體"; //設定字型
32 r.Font.Size =20; //字型大小
33 r.Font.Bold =true; //加粗顯示
34 r.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; //水平置中
35 r.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //垂直置中
36
37 worksheet.Cells[4, 1] ="《歌唱祖國》";
38 worksheet.Cells[5, 2] ="《為中華崛起而讀書》";
39 excelApp.DisplayAlerts =false;
40 excelApp.AlertBeforeOverwriting =false;
41 workBook.Save();
42 excelApp.Quit();
43 System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
44 excelApp =null;
45 System.GC.Collect();
46 }
47 }
48

Program 代碼:

1 class Program
2 {
3 staticvoid Main(string[] args)
4 {
5 Console.Title ="Excel Operation Example";
6 ExcelHelper.SaveData();
7 Environment.Exit(0);
8 }
9 }

 結果:

我愛中華  
 
 
《歌唱祖國》    
  《為中華崛起而讀書》
       
       

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.