1)首先需要
using System.Runtime.InteropServices;
using Excel = Microsoft.Office.Interop.Excel;
using Microsoft.Office.Core;
这三个命名空间,定义一个ExcelManager类文件来管理Excel文件的各种操作。比如打开文件的操作。
/// <summary>
/// Open excel should/must be in the same thread of filling report, so that System.Threading.Thread.CurrentThread.CurrentCulture is set validly
/// </summary>
/// <param name="filePath"></param>
/// <param name="visible"></param>
public void OpenExcel(string filePath, bool visible)
{
if (this.excel == null)
{
if (originalCultureInfo == null)
originalCultureInfo = System.Threading.Thread.CurrentThread.CurrentCulture;//store the culture info for setting back when quit excel applicaton
System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");//filling report under "en- US" culture environment
this.excel = new Excel.ApplicationClass();
this.workbook = excel.Workbooks.Open(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
this.workbook.Saved = true;
if (!excel.ActiveWindow.Zoom.Equals(100.0))
{
this.zoomScalor = excel.ActiveWindow.Zoom;// restore the template zoom scalor
foreach (Excel.Worksheet oneSheet in workbook.Worksheets)
{
if (oneSheet.Visible == Excel.XlSheetVisibility.xlSheetVisible)
{
oneSheet.Activate();
excel.ActiveWindow.Zoom = 100;// to set excel.ActiveWindow.Zoom = 100 is for exactly positioning report images the excel
}
}
}
this.worksheet = (Excel._Worksheet)this.workbook.Sheets[1];
#if DEBUG
this.excel.Visible = true;//alwoays visible for trace and debuging in debug mode
#else
this.excel.Visible = visible;
#endif
if (this.ExcelOpen != null)
this.ExcelOpen();
}
}
2)通过ExcelManager访问各种方法
excelManager = new ExcelManager();
excelManager.OpenExcel(EXCEL_TEMPLATE_NAME, false);
3)Excel文件单元格的读写
excelManager.Worksheet.Cells[dataDetailStartRowIndex, dataDetailStartColumnIndex + 1] = "=SUM(B" + (dataDetailStartRowIndex - countSameMarket).ToString() + ":B" + (dataDetailStartRowIndex - 1).ToString() + ")";
4)Excel文件单元格别名的定义和访问
excelManager.Application.Names.Add("Market1GRPO" + detailRecord.CampaingId, excelManager.Worksheet.get_Range(excelManager.Worksheet.Cells[dataDetailStartRowIndex, dataDetailStartColumnIndex + 1], excelManager.Worksheet.Cells[dataDetailStartRowIndex, dataDetailStartColumnIndex + 1]), true, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);