C# excel 多工作薄操作 部份程式碼

ForTechnology發表於2011-12-01
  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Net.Mail;
using System.Net;
using System.Net.Mime;
using System.Data.OracleClient;
using System.Web;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.IO;
//建立excel新增WorkBook 和WorkSheet
 ApplicationClass excel = new ApplicationClass();
excel.Application.DisplayAlerts = false;
Workbooks workBooks = excel.Workbooks;
Workbook workBook = workBooks.Add(true);
excel.DisplayAlerts = false;
excel.Visible = false;
Missing missing = Missing.Value;

//新增工作薄
 workBook.Worksheets.Add(Type.Missing, workBook.Worksheets[iSheetCount], 1, Type.Missing);
 tempSheet = (Worksheet)workBook.Worksheets[iSheetCount + 1];
//設定部份樣式
//表頭
sheet.get_Range(excel.Cells[iBasePos[0] - 1, iBasePos[1] + 1], excel.Cells[iBasePos[0], iBasePos[1] + dtResult.Columns.Count]).Merge(0);
sheet.Cells[iBasePos[0] - 1, iBasePos[1] + 1] = "Fresh Yield Report  For處級部級";
sheet.get_Range(excel.Cells[iBasePos[0] - 1, iBasePos[1] + 1], excel.Cells[iBasePos[0] - 1, iBasePos[1] + 1]).Font.Bold = true;
 sheet.get_Range(excel.Cells[iBasePos[0] - 1, iBasePos[1] + 1], excel.Cells[iBasePos[0] - 1, iBasePos[1] + 1]).Font.Size = 14;
 //設定表格為最適應寬度
   sheet.get_Range(excel.Cells[iBasePos[0] + 1, iBasePos[1] + 1], excel.Cells[iBasePos[0] + dtResult.Rows.Count + 1, iBasePos[1] + dtResult.Columns.Count]).Columns.AutoFit();
 //設定欄位顏色
 sheet.get_Range(excel.Cells[iBasePos[0] + 1, iBasePos[1] + 1], excel.Cells[iBasePos[0] + 1, iBasePos[1] + dtResult.Columns.Count]).Interior.ColorIndex = 16;
                sheet.get_Range(excel.Cells[iBasePos[0] + 2, iBasePos[1] + 1], excel.Cells[iBasePos[0] + dtResult.Rows.Count + 1, iBasePos[1] + 1]).Interior.ColorIndex = 16;
 //居中
                sheet.get_Range(excel.Cells[1, 1], excel.Cells[iBasePos[0] + dtResult.Rows.Count + 4, iBasePos[1] + dtResult.Columns.Count]).HorizontalAlignment = XlVAlign.xlVAlignCenter;
                sheet.get_Range(excel.Cells[1, 1], excel.Cells[iBasePos[0] + dtResult.Rows.Count + 4, iBasePos[1] + dtResult.Columns.Count]).VerticalAlignment = XlVAlign.xlVAlignCenter;
//邊框
                sheet.get_Range(excel.Cells[iBasePos[0] + 1, iBasePos[1] + 1], excel.Cells[iBasePos[0] + dtResult.Rows.Count + 1, iBasePos[1] + dtResult.Columns.Count]).Borders.LineStyle. = 1;
//儲存
workBook.SaveAs(m_FilePath, missing, missing, missing, missing, missing, XlSaveAsAccessMode.xlShared, missing, missing, missing, missing, missing);
workBooks.Close();
excel.Quit();


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/25897606/viewspace-712497/,如需轉載,請註明出處,否則將追究法律責任。

相關文章