using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Office.Interop.Excel;
/// <summary>
/// ExcelHandler 的摘要说明
/// </summary>
public class ExcelHandler
{
public ExcelHandler(string fileName)
{
if (!Initial())
return;
excelFileName = fileName;
//加入新的WorkBook
//获取WorkBooks集合
workbooks = excelApp.Workbooks;
if (!System.IO.File.Exists(fileName))
{//create a new xls file(XlWBATemplate.xlWBATWorksheet
workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
}
else
//*修改原有文件
workbook = workbooks.Add(excelFileName);
//获取WorkSheets集合
sheets = workbook.Worksheets;
worksheet = (Worksheet)sheets.get_Item(1);
if (worksheet == null)
{
System.Web.HttpContext.Current.Response.Write("worksheet is null!");
return;
}
}
public void Dispose()
{
if (isInitialed && excelApp != null)
excelApp.Quit();
}
public bool Initial()
{
if (!isInitialed)
{
excelApp = new Microsoft.Office.Interop.Excel.Application();
if (excelApp == null)
{
System.Web.HttpContext.Current.Response.Write("Excel couldn't be started!");
return false;
}
excelApp.DisplayAlerts = false;
isInitialed = true;
}
return true;
}
private static Microsoft.Office.Interop.Excel.Application excelApp;
private Microsoft.Office.Interop.Excel.Workbooks workbooks;
private Microsoft.Office.Interop.Excel.Workbook workbook;
private Sheets sheets;
private Worksheet worksheet;
private string excelFileName;
private static bool isInitialed = false;
public void Write(int row, int column, object val)
{
worksheet.Cells[row, column] = val;
}
public object Read(int row, int column)
{
return worksheet.Cells[row, column];
}
public void Save()
{
if (!workbook.Saved)
{
workbook.Close(true, excelFileName, true);
}
}
}