froster

博客园 首页 新随笔 联系 订阅 管理
using Microsoft.Office.Interop.Excel;
namespace FileHandler
{
    
public class ExcelFile
    
{
        
public ExcelFile(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
            

                MessageBox.Show(
"worksheet is null!","Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
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
                

                    MessageBox.Show(
"Excel couldn't be started!","Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    
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);
            }

        }

    }

}
posted on 2005-03-30 20:43  大牛  阅读(4047)  评论(4编辑  收藏  举报