vs2008 C# 對excel操作
最新需要用excel寫一個機器故障統計表,由於輸入數據很多,所以決定自己寫程序生成一個。本文主要介紹了生成的方法。
一、 需求,VS2008和office2003.
二、 打開VS2008。文件--->新建項目--->其他語言--->visualC#--->office--->2003對話框中選擇Excel2003外接程序。在private void ThisAddIn_Startup(object sender, System.EventArgse)中輸入程序:
int i, j;
stringblad = "c";
Excel.ApplicationClass myexcel = new Excel.ApplicationClass();//創建excel對象
Excel.Workbook firstbook = myexcel.Workbooks.Add(true);//創建工作薄
Excel.Worksheet firstsheet = (Excel.Worksheet)firstbook.ActiveSheet;//創建工作表
//設置標題
Excel.Range title =firstsheet.get_Range(firstsheet.Cells[1, 1], firstsheet.Cells[1, 50]);//選取單元格
title.Merge(true);//合併單元格
title.Value2 = "機器故障表";//設置單元格內文本
title.Font.Name = "宋體";//設置文本字體
title.Font.Size = 20;//設置字體大小
title.Font.Bold = true;//字體加粗顯示
title.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;//水平居中
title.VerticalAlignment= Excel.XlVAlign.xlVAlignCenter;//垂直居中
title.Borders.LineStyle= Excel.XlLineStyle.xlContinuous;//設置邊框類型
title.Borders.Weight =Excel.XlBorderWeight.xlMedium;//邊框常規粗細
//填充數據
for(i = 0; i < 16; i++)
{
for (j =1; j < 21; j++)
{
blad = blad + (i+ 1);
blad = blad + "b";
blad = blad + j;
firstsheet.Cells[i * 20 + j + 2, 1] = blad;
blad = "c";
}
}
myexcel.DisplayAlerts = false;//禁止彈出警告提示
myexcel.AlertBeforeOverwriting = false;//禁止寫覆蓋警告
firstbook.Save();
myexcel.Visible = true; //設置可見
myexcel.ActiveWorkbook.SaveCopyAs("D:\\firstfile.xls");//這條語句很關鍵,沒有它會提示保存修改
firstbook.Close(missing,missing, missing);
myexcel.workboos
myexcel.Quit();
三、 其他office excel的操作;
myexcel.Workbooks.Open();//打開已經存在的xls
firstsheet.Columns.ColumnWidth= 5;//設置列的寬度
firstsheet.Rows.RowHeight = 1;//設置行的高度
firstsheet.Rows.Insert();//插入行
firstsheet.Columns.Insert();//插入列
具體的操作可以在VS2008中用”.”引出所含成員的辦法來尋找所需功能。