using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Office.Interop.Excel; using System.IO; namespace ConsoleApplication1 { class ExcelWrt //參考http://www.dotblogs.com.tw/yc421206/archive/2009/01/11/6727.aspx { const int groups=8; const int columnOffset = 3; const int rowOffset = 2; //引用Excel Application類別 ApplicationClass myExcel = new ApplicationClass(); //引用活頁簿類別 Workbook myBook = null; //引用工作表類別 Worksheet mySheet = null; //引用Range類別 Range myRange = null; public ExcelWrt(int numberLength,string[] show) { int i; //加入新的活頁簿 myExcel.Workbooks.Add(true); myExcel.DisplayAlerts = false;//停用警告訊息 //myExcel.Visible = true; //讓excel可見 myBook = myExcel.Workbooks[1];//取用第一個book // myBook.Activate();//設定活頁簿焦點 mySheet = (Worksheet)myBook.Worksheets[1];//取用地一個工作簿 mySheet.Name = "組合"; //mySheet.get_Range(myExcel.Cells[1, 1], myExcel.Cells[14, 8]).BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThin, XlColorIndex.xlColorIndexAutomatic, null); //myRange.Borders.Weight = 2; myExcel.Cells[1,1]="項目"; myExcel.Cells[1,2]="號碼"; myExcel.Cells[1,3] = "組數"; for (i = 1; i <= numberLength; i++) { myExcel.Cells[i + 1, 1] = i; myExcel.Cells[i + 1, 2] = show[i-1]; } //mySheet.Activate();//設定工作簿焦點 } public void GetExcel(int groupNumber,string[] groupMember,int choiceNumber) { //將數據填入 myExcel.Cells[((groupNumber - 1) / groups) * (choiceNumber + 1) + rowOffset, ((groupNumber - 1) % groups) + columnOffset] = "第 " + groupNumber.ToString() + " 組"; for (int i = 0; i < choiceNumber; i++) { myExcel.Cells[i + ((groupNumber - 1) / groups) * (choiceNumber + 1) + rowOffset + 1, ((groupNumber - 1) % groups) + columnOffset] = groupMember[i]; } } public void SaveExcel(int count,int choiceNumber) { //劃線 = = mySheet.get_Range(myExcel.Cells[1, 1], myExcel.Cells[((count - 1) / groups + 1) * (choiceNumber + 1) + 1, groups + columnOffset-1]).Borders.Weight = 2; mySheet.get_Range(myExcel.Cells[1, columnOffset], myExcel.Cells[1, groups + columnOffset-1]).Merge(true); mySheet.get_Range(myExcel.Cells[1, 1], myExcel.Cells[((count - 1) / groups + 1) * (choiceNumber + 1) + 1, groups + columnOffset - 1]).HorizontalAlignment =XlHAlign.xlHAlignCenter;//置中對齊 //設定儲存路徑 string PathFile = Directory.GetCurrentDirectory() + @"\button4.xls"; try { //另存活頁簿 myBook.SaveAs(PathFile, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing , XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //關閉活頁簿 myBook.Close(false, Type.Missing, Type.Missing); //關閉Excel myExcel.Quit(); //釋放Excel資源 System.Runtime.InteropServices.Marshal.ReleaseComObject(myExcel); myBook = null; mySheet = null; myRange = null; myExcel = null; GC.Collect(); } catch(System.Runtime.InteropServices.COMException ex1){ Console.WriteLine(ex1); } } } }
星期一, 8月 02, 2010
c# 測試
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言