操作Excel类库

using System;
using System.Text;
using System.Reflection;
using System.Runtime.InteropServices;
using Excel;

namespace MOS
{
    
/// <summary>
    
/// ExcelHelp 的摘要说明。
    
/// </summary>
    public class ExcelHelp
    {
        
private Excel.Application _exFile;
        
private int sheetIndex = 1;
        
private string strFileName = "";
        
public ExcelHelp()
        {
            _exFile 
= new Excel.ApplicationClass();
                
//.Application();
            
//_exFile.DisplayAlerts = false;
            
//_exFile.AskToUpdateLinks = false;
            
//_exFile.AlertBeforeOverwriting = false;
            _exFile.Visible=true;
        }
        
public string FileName
        {
            
get
            {
                
return this.strFileName;
            }
            
set
            {
                
this.strFileName = value;
            }
        }
        
private Excel._Workbook _workBook;
        
public Excel._Workbook    WorkBook
        {
            
get
            {
                
return _workBook;
            }
            
set
            {
                _workBook 
= value;
            }

        }
        
public void Save()
        {
            
try
            {
                _workBook.SaveAs(
this.strFileName ,Excel.XlFileFormat.xlWorkbookNormal,Missing.Value ,Missing.Value ,
                    Missing.Value ,Missing.Value ,Excel.XlSaveAsAccessMode.xlNoChange,Missing.Value ,Missing.Value ,Missing.Value ,
                    Missing.Value,Missing.Value 
//#if _EXCEL_2003
//                    ,Missing.Value 
//                
//#endif
                    
                    );
            }
            
catch(Exception e)
            {
                
throw e;
            }

        }
        
/// <summary>
        
/// Read onc cell in the current sheet.
        
/// </summary>
        
/// <param name="row">row of current sheet</param>
        
/// <param name="col">col of current sheet</param>
        
/// <returns></returns>
        public string ReadCell(int row ,int col)
        {
            
try
            {
                
if (_workBook!=null)
                {
                    Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(sheetIndex);
                    _workSheet.Activate();
                    
// convert cell position to cell name.(for example : A1,C3 ect.)
                    string rangeCell =  this.Convert(col).ToString() + row.ToString();
                    
// get ramge date collection.
                    Excel.Range rg = _workSheet.get_Range (rangeCell,rangeCell);
                    rg.Activate();
                    
// get present cell date

                    
//                    object objValue = rg.Value2;
                    
//                    object objValue = rg.get_Item(row,col);
                    object objValue = rg.Value2;
                    
                    
if (objValue == null)
                    {
                        objValue 
= "";
                    }
                    
return objValue.ToString();

                }
                
else
                    
return "";
            }
            
catch(Exception e)
            {
                
throw e;
            }
        }


        
public string [] ReadOneRowCell(int row ,int colStart, int colEnd)
        {
            
string [] result = new string[ colEnd - colStart + 1];
            
try
            {
                
if (_workBook != null)
                {
                    Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(sheetIndex);
                    _workSheet.Activate();
                    
// convert cell position to cell name.(for example : A1,C3 ect.)

                    
forint col = colStart; col <= colEnd; col++ )
                    {
                        
string rangeCell =  this.Convert(col).ToString() + row.ToString();
                        
// get ramge date collection.
                        Excel.Range rg = _workSheet.get_Range (rangeCell,rangeCell);
                        rg.Activate();
                        
// get present cell date

                        
//                    object objValue = rg.Value2;
                        
//                    object objValue = rg.get_Item(row,col);
                        object objValue = rg.Value2;
                    
                        
if (objValue == null)
                        {
                            objValue 
= "";
                        }
                        result[ col
-colStart ] = objValue.ToString();
    
                    }
                    
return result;
                }
                
else
                    
return null;
            }
            
catch(Exception e)
            {
                
throw e;
            }
        }

        
/// <summary>
        
/// Read onc cell in the current sheet.
        
/// </summary>
        
/// <param name="row">row of current sheet</param>
        
/// <param name="col">col of current sheet</param>
        
/// <returns></returns>
        public object ReadObjCell(int row ,int col)
        {
            
try
            {
                
if (_workBook!=null)
                {
                    Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(sheetIndex);
                    _workSheet.Activate();
                    
// convert cell position to cell name.(for example : A1,C3 ect.)
                    string rangeCell =  this.Convert(col).ToString() + row.ToString();
                    
// get ramge date collection.
                    Excel.Range rg = _workSheet.get_Range (rangeCell,rangeCell);
                    rg.Activate();
                    
// get present cell date

                    
//                    object objValue = rg.Value2;
                    object objValue = rg.get_Item(row,col);

                    
return objValue;
                }
                
else
                    
return null;
            }
            
catch(Exception e)
            {
                
throw e;
            }
        }

        
/// <summary>
        
/// write date to a cell.
        
/// </summary>
        
/// <param name="row">row of current sheet</param>
        
/// <param name="col">col of current sheet</param>
        
/// <param name="cellObj">the date that will be insert into excel file</param>
        
/// <returns>true:success.</returns>
        public bool WriteCell(int row, int col, string cellObj)
        {
            
try
            {
                
if (!(_workBook==null))
                {
                    Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(sheetIndex);
                    _workSheet.Activate();
                    _workSheet.Cells[row,col] 
= cellObj;
                    
return true;
                }
                
else
                    
return false;
            }
            
catch(Exception e)
            {
                
throw e;
            }
        }

        
public bool WriteCell(int row, int col, object cellObj)
        {
            
try
            {
                
if (!(_workBook==null))
                {
                    Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(sheetIndex);
                    _workSheet.Activate();
                    
string rangeCell =  this.Convert(col).ToString() + row.ToString();
                    Excel.Range rg 
= _workSheet.get_Range (rangeCell,rangeCell);
                    rg.Activate();
                    rg.set_Item(row,col,cellObj);
                    
//_workSheet.Activate();
                    
//_workSheet.Cells[row,col] = cellObj;
                    return true;
                }
                
else
                    
return false;
            }
            
catch(Exception e)
            {
                
throw e;
            }
        }

        
/// <summary>
        
/// set excel file open and display style.
        
/// </summary>
        
/// <returns></returns>
        public bool SetCellStyle()
        {
            _exFile.DisplayAlerts 
= false;
            _exFile.Visible 
= false;
            
return true;
        }

        
/// <summary>
        
/// Excel file name. compose of datetime and random integer.
        
/// </summary>
        
/// <returns></returns>
        private string GetFileName()
        {
            StringBuilder strFileName
= new StringBuilder();
            DateTime dtNow 
= DateTime.Now;
            strFileName.Append (dtNow.Year.ToString().Substring(
2,2));
            strFileName.Append (dtNow.Month.ToString());
            strFileName.Append (dtNow.Day.ToString());
            strFileName.Append (dtNow.Hour.ToString());
            strFileName.Append (dtNow.Minute.ToString());
            strFileName.Append (dtNow.Second.ToString());
            strFileName.Append (
"-");
            System.Random rd 
= new Random(0);
            strFileName.Append (rd.Next(
9).ToString());
            strFileName.Append (rd.Next(
9).ToString());
            
return strFileName.ToString();
        }

        
// set or get sheet index.
        public int SheetIndex
        {
            
get
            {
                
return this.sheetIndex;
            }
            
set
            {
                
this.sheetIndex = value;
            }
        }

        
// set or get sheet name
        public string SheetName
        {
            
get
            {
                Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(sheetIndex);
                
return _workSheet.Name;
            }
            
set
            {
                
if (_workBook!=null)
                {
                    sheetIndex 
= 0;
                    
int iCount =_workBook.Worksheets.Count;
                    
for (int i = 0; i < iCount; i++)
                    {
                        Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(i+1);
                        
if (_workSheet.Name == value)
                        {
                            sheetIndex 
= i+1;
                            
break;
                        }
                    }
                }
            }
        }

        
/// <summary>
        
/// 得到Excel文件中的Sheet数
        
/// </summary>
        
/// <returns></returns>
        public int GetSheetCount ()
        {
            
return _workBook.Worksheets.Count;
        }

        
/// <summary>
        
/// 得到某个sheet的名字
        
/// </summary>
        
/// <param name="index"></param>
        
/// <returns></returns>
        public string GetSheetName (int index)
        {
            Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(index);
            
return _workSheet.Name;
        }
        
/// <summary>
        
/// 为文件中的sheet指定sheet name
        
/// </summary>
        
/// <param name="index"></param>
        
/// <param name="strSheetName"></param>
        public void SetSheetName (int index, string strSheetName)
        {
            Excel._Worksheet _workSheet 
= (Excel._Worksheet)_workBook.Worksheets.get_Item(index);
            _workSheet.Name 
= strSheetName;
        }

        
// convert row sign.
        public string Convert(int index)
        {
            
int _index = index<=0?0:index>255?254:index-1;
            
return table[_index];
        }

        
private static readonly string[] table = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","AA","AB","AC","AD","AE","AF","AG","AH","AI","AJ","AK","AL","AM","AN","AO","AP","AQ","AR","AS","AT","AU","AV","AW","AX","AY","AZ","BA","BB","BC","BD","BE","BF","BG","BH","BI","BJ","BK","BL","BM","BN","BO","BP","BQ","BR","BS","BT","BU","BV","BW","BX","BY","BZ","CA","CB","CC","CD","CE","CF","CG","CH","CI","CJ","CK","CL","CM","CN","CO","CP","CQ","CR","CS","CT","CU","CV","CW","CX","CY","CZ","DA","DB","DC","DD","DE","DF","DG","DH","DI","DJ","DK","DL","DM","DN","DO","DP","DQ","DR","DS","DT","DU","DV","DW","DX","DY","DZ","EA","EB","EC","ED","EE","EF","EG","EH","EI","EJ","EK","EL","EM","EN","EO","EP","EQ","ER","ES","ET","EU","EV","EW","EX","EY","EZ","FA","FB","FC","FD","FE","FF","FG","FH","FI","FJ","FK","FL","FM","FN","FO","FP","FQ","FR","FS","FT","FU","FV","FW","FX","FY","FZ","GA","GB","GC","GD","GE","GF","GG","GH","GI","GJ","GK","GL","GM","GN","GO","GP","GQ","GR","GS","GT","GU","GV","GW","GX","GY","GZ","HA","HB","HC","HD","HE","HF","HG","HH","HI","HJ","HK","HL","HM","HN","HO","HP","HQ","HR","HS","HT","HU","HV","HW","HX","HY","HZ","IA","IB","IC","ID","IE","IF","IG","IH","II","IJ","IK","IL","IM","IN","IO","IP","IQ","IR","IS","IT","IU","IV"};
        
public void CloseFile(bool SaveChange)
        {
            
try
            {
                
if (_workBook!=null  || !_workBook.ReadOnly)
                {
                    
//close excel file.
                    _workBook.Close(SaveChange,Missing.Value,Missing.Value);
                    
// release com object
                    Marshal.ReleaseComObject(_workBook);
                    _workBook 
= null;
                }
                
// release excel process.
                _exFile.Quit();
                Marshal.ReleaseComObject (_exFile);
                _exFile 
= null;
            }
            
catch(Exception e)
            {
                
throw e;
            }
        }
        
public void OpenFile(string FileName)
        {
            
try
            {
                
                
                _workBook 
= _exFile.Workbooks.Open(FileName,
                    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);
            }
            
catch(Exception e)
            {
                
throw e;
            }
            
this.strFileName = FileName;
        }
    }
}
权限问题:
<identity impersonate="true" userName="administrator" password="" />
下载excel.dll
原文地址:https://www.cnblogs.com/jasonduan/p/409057.html