c#導出Excel數據之常用對象

需要引入Microsoft Office 11.0 Object LibraryCOM組件

 

           // 定義Application 對象,此對象表示整個Excel 程序

            Excel.Application ExApp = new Excel.Application();

 

            if (ExApp == null)

            {

                MessageBox.Show("無法創建Excel對象,可能你的電腦未安裝Excel或你的Excel版本不是Office2003的!");

                return;

            }

 

            //程序運行方式爲前臺顯示

            ExApp.Visible = true;

 

            //定義的Excel工作對象

            Excel.Workbooks ExBooks = ExApp.Workbooks;

            Excel.Workbook ExBook = ExBooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);

 

            // 定義Worksheet 對象,此對象表示Execel 中的第一張工作表

            Excel.Worksheet ExSheet = (Excel.Worksheet)ExBook.Worksheets[1];

            // 命名工作表的名稱爲 "工作表一"

            ExSheet.Name = "工作表一";

            //設置單元格格式爲文本格式

     ExSheet.Cells.NumberFormatLocal := '@' ;

 

            //設置單元格的值

            ExSheet.Cells[1, 3] = "江波";

 

            //選擇單元格

            Excel.Range range = ExSheet.get_Range(ExSheet.Cells[5, 6], ExSheet.Cells[8, 9]);

            //合併單元格

            range.Merge(System.Reflection.Missing.Value);

            //選中的單元格內的值

            range.Value2 = "QQ;261025448";

            //設置內容對齊方式爲居中

            range.HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;

 

            #region 調整單元格格式,並保存文件

            ExSheet.Cells.EntireColumn.AutoFit();

            ExBook.Saved = true;

            ExBook.SaveCopyAs("C:\\test.xls");

            System.Runtime.InteropServices.Marshal.ReleaseComObject(ExSheet);

            ExSheet = null;

            Marshal.ReleaseComObject(ExBook);

            ExBook = null;

            ExBooks.Close();

            Marshal.ReleaseComObject(ExBooks);

            ExBooks = null;

            ExApp.Quit();

            Marshal.ReleaseComObject(ExApp);

            ExApp = null;

            #endregion

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章