自己用的c#操作excel類。

下面的程序,是自己經常用到的excel操作類,本程序與別的對excel操作唯一改進的地方是對excel數據的填充方式上。

網上經常看到的填充方式有:

1:按單元格

2:按區域(range)

本程序,也還是按區域來填充的,只需要參數是一個datatable就行了

using System;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Data;
using Excel = Microsoft.Office.Interop.Excel;

namespace  KernelCore.Utility.Excel2007
{
    
#region 操作Excle應用程序類
    
/*
     //調用例子:
     Excel._Application   spExcelApp=new Excel.ApplicationClass();

     //模板文件
     Excel._Workbook spMouleBook = CExcelApp.OpenExcel(spExcelApp,"c:/Empty.xls");
     // Excel._Worksheet spMouleSheet=CExcelApp.GetSheetItem(spMouleBook,1);
    
     //輸出文件
     Excel._Workbook  spOutBook =CExcelApp.AddSheetPage(spExcelApp);
     Excel._Worksheet spOutSheet =CExcelApp.GetSheetItem(spOutBook,1);
     Excel._Worksheet spOutSheet1 =CExcelApp.GetSheetItem(spOutBook,2);

     spOutSheet.Name="SheetName";

            
     //更新所有列寬
     //CExcelApp.SetColumnWidth(spMouleSheet,1,spOutSheet,1,11);

     //整行拷貝
     //Excel.Range spSou = CExcelApp.GetRangeByRow(spMouleSheet,1,1000);

     //Excel.Range spDes =CExcelApp.GetRangeByRow(spOutSheet,1);
     //CExcelApp.CopyRange(spSou,spDes);
     object spRgBeg = CExcelApp.GetRange(spOutSheet,1,1);
     object spRgEnd = CExcelApp.GetRange(spOutSheet,60000,18);
     spOutSheet.get_Range(spRgBeg,spRgEnd).set_Value(System.Reflection.Missing.Value,CExcelApp.GetRangeDataArr(GetJsTable()));

     object spRgBeg1 = CExcelApp.GetRange(spOutSheet1,1,1);
     object spRgEnd1 = CExcelApp.GetRange(spOutSheet1,60000,18);

     spOutSheet1.get_Range(spRgBeg1,spRgEnd1).set_Value(System.Reflection.Missing.Value,CExcelApp.GetRangeDataArr(GetJsTable()));

     //CExcelApp.Show(spExcelApp,true);  //是否顯示Excel
     CExcelApp.SaveAs(spOutBook,"d:/z.xls");

     CExcelApp.CloseBook(spMouleBook,false);
     CExcelApp.CloseBook(spOutBook,false);

     CExcelApp.ReleaseSheet(spOutSheet);
     CExcelApp.ReleaseSheet(spOutSheet1);
     CExcelApp.ReleaseBook(spOutBook);
     CExcelApp.ReleaseBook(spMouleBook);
     CExcelApp.ReleaseExcelApp(spExcelApp);
     GC.Collect();
 
*/


    
/// <summary>
    
/// CExcelComm 的摘要說明。
    
/// </summary>
    public class CExcelApp
    {
        
/// <summary>
        
/// 創建Excel相關對象
        
/// </summary>
        static public Excel._Workbook OpenExcel(Excel._Application spExcelApp, string strFilePath)
        {
            
try
            {
                
if (strFilePath == "")
                    
return null;
                Object vtMissing 
= System.Reflection.Missing.Value;
                
if (spExcelApp == null)
                {
                    
return null;
                }
                Excel._Workbook m_spWorkBook 
= spExcelApp.Workbooks.Open(strFilePath, vtMissing, vtMissing, vtMissing,
                    vtMissing, vtMissing, vtMissing, vtMissing, vtMissing,
                    vtMissing, vtMissing, vtMissing, vtMissing, vtMissing, 
0);

                
return m_spWorkBook;

            }
            
catch (Exception ex)
            {
                
string strError = ex.ToString().Trim();
                
return null;
            }
        }


        
/// <summary>
        
/// 是否顯示Excel
        
/// </summary>
        static public void Show(Excel._Application pApp, bool bShow)
        {
            
if (pApp == nullreturn;
            pApp.Visible 
= bShow ? true : false;
        }


        
/// <summary>
        
/// 根據Sheet的Index得到WorkSheet對象
        
/// </summary>
        static public Excel._Worksheet GetSheetItem(Excel._Workbook spWorkBook, int iIndex)
        {
            
try
            {
                
if (spWorkBook == null)
                {
                    
return null;
                }
                
return (Excel._Worksheet)spWorkBook.Sheets.get_Item(iIndex);
            }

            
catch (Exception ex)
            {
                
string strError = ex.ToString().Trim();
                
return null;
            }

        }

        
/// <summary>
        
/// 得到打開Excel模板的Sheet個數
        
/// </summary>
        static public int GetSheetCount(Excel._Workbook spWorkBook)
        {
            
try
            {
                
if (spWorkBook == null)
                {
                    
return -1;
                }
                
return spWorkBook.Sheets.Count;
            }

            
catch (Exception ex)
            {
                
string strError = ex.ToString().Trim();
                
return -1;
            }
        }

        
/// <summary>
        
///    從頁中獲得對應值
        
/// </summary>
        static public bool GetValueFromSheet(Excel._Worksheet pSheet, long nRow, long nCol, ref string sValue)
        {
            
return CExcelApp.GetCellValue(pSheet, nRow, nCol, ref sValue);
            
//return true;
        }

        
/// <summary>
        
///    設置值到指定頁上
        
/// </summary>
        static public bool SetValueToSheet(Excel._Worksheet pSheet, long nRow, long nCol, double dValue)
        {
            Excel.Range spRange 
= CExcelApp.GetRange(pSheet, nRow, nCol);
            
if (spRange == null)
                
return false;

            
return CExcelApp.SetCellValue(spRange, dValue);
        }



        
/// <summary>
        
/// 根據Sheet和ExRange,獲得指定項的值
        
/// </summary>
        static public bool GetCellValue(Excel._Worksheet pSheet,   //指定頁
            long nRow,                 //指定項
            long nCol,
            
ref string strValue         //返回值
            )
        {
            Excel.Range spRange 
= GetRange(pSheet, nRow, nCol);
            
if (spRange == null)
                
return false;
            
return GetCellValue(spRange, ref strValue);
        }

        
/// <summary>
        
/// 獲得指定Range項得到相應的值
        
/// </summary>
        static public bool GetCellValue(Excel.Range pRange,     //指定項
            ref string strValue       //返回值
            )
        {
            Object[,] saRet;
            
string strRet = "";
            saRet 
= (System.Object[,])pRange.get_Value(System.Reflection.Missing.Value);
            
try
            {
                
long iRows;
                
long iCols;
                iRows 
= saRet.GetUpperBound(0);
                iCols 
= saRet.GetUpperBound(1);

                
for (long row = 1; row <= iRows; row++)
                {
                    
for (long col = 1; col <= iCols; col++)
                    {
                        
if (saRet[row, col] != "")
                            strRet 
+= saRet[row, col] + ",";
                    }
                }
                
string[] strRes = strRet.Split(',');
                
for (int i = 0; i < strRes.Length - 1; i++)
                {
                    
if (strRes[i] != "")
                        strValue 
+= strRes[i] + ",";
                }
            }
            
catch (Exception ex)
            {
                ex.ToString().Trim();
            }
            
return true;
        }


        
/// <summary>
        
///  根據Excle頁和Range和值設置Cell字符串
        
/// </summary>
        static public bool SetCellValue(Excel._Worksheet pSheet,        //指定頁
            long nRow,       //
            long nCol,         //
            string szText        //更新值,爲空時設置項目爲空
            )
        {
            
if (pSheet == null || Invalid(nRow, nCol))
                
return false;

            Excel.Range spRange 
= (Excel.Range)pSheet.Cells.get_Item(nRow, nCol);
            
if (spRange != null)
                
return SetCellValue(spRange, szText);
            
return false;
        }



        
/// <summary>
        
/// 根據Range和值設置Cell字符串
        
/// </summary>
        static public bool SetCellValue(Excel.Range pRange,     //指定項
            string szText              //更新值,爲空時設置項目爲空
            )
        {
            
if (szText != null)
                pRange.set_Value(System.Reflection.Missing.Value, szText);

            
return true;
        }


        
//設置指定範圍的值
        /// <summary>
        
/// 根據指定的頁的起始項和結束項字符串
        
/// </summary>
        static public bool SetRangeValue(Excel._Worksheet pSheet,        //指定頁  //指定起始項,包括該項                                                          
            long nBegRow,
            
long nBegCol,
            
long nEndRow,
            
long nEndCol,
            
string szText       //更新值,爲空時設置項目爲空
            )
        {
            
if (pSheet == null)
                
return false;

            
if (Invalid(nBegRow, nBegCol) || Invalid(nEndRow, nEndCol))
                
return false;

            
for (long i = nBegRow; i <= nEndRow; i++)
            {
                
for (long j = nBegCol; j <= nEndCol; j++)
                {
                    SetCellValue(pSheet, i, j, szText);
                }
            }

            
return true;
        }


        
/// <summary>
        
/// 根據Range和值設置Cell double值
        
/// </summary>
        static public bool SetCellValue(Excel.Range pRange,             //指定項
            double dValue                    //更新值,爲空時設置項目爲空
            )
        {
            pRange.set_Value(System.Reflection.Missing.Value, dValue);
            
return true;
        }


        
/// <summary>
        
/// 根據指定起始和終止範圍,獲得 Range 對象
        
/// </summary>
        static public Excel.Range GetRange(Excel._Worksheet pSheet,     //指定頁
            long nBegRow, //指定起始項,包括該項
            long nBegCol,
            
long nEndRow,//指定結束項,包括該項
            long nEndCol
            )
        {
            
if (pSheet == null || Invalid(nBegRow, nBegCol) || Invalid(nEndRow, nEndCol))
                
return null;

            
object spRgBeg = GetRange(pSheet, nBegRow, nBegCol);
            
if (spRgBeg == nullreturn null;
            
object spRgEnd = GetRange(pSheet, nEndRow, nEndCol);
            
if (spRgEnd == nullreturn null;
            
return pSheet.get_Range(spRgBeg, spRgEnd);
        }



        
/// <summary>
        
/// 根據指定行,獲得 Range 對象
        
/// </summary>
        static public Excel.Range GetRangeByRow(Excel._Worksheet pSheet,      //指定的頁
            long nRow                       //指定起始行
            )
        {
            
if (nRow < 1 || nRow > 0xFFFF)
                
return null;

            
return (Excel.Range)pSheet.Rows.get_Item(nRow, System.Reflection.Missing.Value);
        }

        
/// <summary>
        
/// 根據指定頁和行,獲得 Range 對象
        
/// </summary>
        static public Excel.Range GetRangeByRow(Excel._Worksheet pSheet,      //指定的頁
            long nRowBeg,                  //指定起始項,包括該項
            long nRowEnd                  //指定結束項,包括該項
            )
        {
            
object spRgBeg = GetRangeByRow(pSheet, nRowBeg);
            
object spRgEnd = GetRangeByRow(pSheet, nRowEnd);
            
return pSheet.get_Range(spRgBeg, spRgEnd);
        }

        
/// <summary>
        
/// 根據指定列,獲得 Range 對象
        
/// </summary>
        static public Excel.Range GetRangeByCol(Excel._Worksheet pSheet,      //指定的頁
            long nCol                    //指定起始列
            )
        {
            
if (nCol < 1 || nCol > 0xFF)
                
return null;

            
return (Excel.Range)pSheet.Columns.get_Item(nCol, System.Reflection.Missing.Value);
        }

        
/// <summary>
        
/// 指定行及結束行
        
/// </summary>

        
static public Excel.Range GetRangeByCol(Excel._Worksheet pSheet,       //指定的頁
            long nColBeg,                       //指定起始項,包括該項
            long nColEnd                       //指定結束項,包括該項
            )
        {
            
object spRgBeg = GetRangeByCol(pSheet, nColBeg);
            
object spRgEnd = GetRangeByCol(pSheet, nColEnd);

            
return pSheet.get_Range(spRgBeg, spRgEnd);
        }


        
/// <summary>
        
/// 根據指定頁和Cell,獲得 Range 對象
        
/// </summary>
        static public Excel.Range GetRange(Excel._Worksheet pSheet,
            
long nRow, long nCol
            )
        {
            
if (pSheet != null && Invalid(nRow, nCol) == false)
                
return (Excel.Range)pSheet.Cells.get_Item(nRow, nCol);
            
return null;
        }


        
/// <summary>
        
/// 拷貝範圍的項到目標項
        
/// </summary>
        static public bool CopyRange(Excel.Range pSou,        //數據源
            Excel.Range pDes        //目標
            )
        {

            Excel.Range spDes 
= pDes;
            
object spDis = spDes;
            pSou.Copy(spDis);
            
return true;

        }



        
/// <summary>
        
/// 設置指定列的寬度
        
/// </summary>
        static public bool SetColumnWidth(Excel.Range pCol, ref double dWidth)
        {
            dWidth 
= (double)pCol.ColumnWidth;
            
return true;
        }


        
/// <summary>
        
/// 更新指定列的寬度
        
/// </summary>
        static public bool SetColumnWidth(Excel.Range pRange, double dWidth)
        {
            pRange.ColumnWidth 
= dWidth;
            
return true;
        }


        
/// <summary>
        
/// 設置數據源和目標源的寬度相同
        
/// </summary>
        static public bool SetColumnWidth(Excel.Range pSou, Excel.Range pDes)
        {
            pDes.ColumnWidth 
= pSou.ColumnWidth;
            
return true;
        }

        
/// <summary>
        
/// 批量更新指定範圍內的列與數據源同範圍內的相同
        
/// </summary>
        static public bool SetColumnWidth(Excel._Worksheet pSheetSou,    //數據源頁
            long nColBegSou,                    //數據源的起始列,包括該列
            Excel._Worksheet pSheetDes,    //目標源頁
            long nColBegDes,                    //目標源的起始列,包括該列
            long nCount                        //需要更新的列數
            )
        {
            Excel.Range spSou, spDes;
            
long nSou = nColBegSou;
            
long nDes = nColBegDes;
            
for (long i = 0; i < nCount; i++, nSou++, nDes++)
            {
                spSou 
= GetRangeByCol(pSheetSou, nSou);
                spDes 
= GetRangeByCol(pSheetDes, nDes);
                SetColumnWidth(spSou, spDes);
            }
            
return true;
        }


        
/// <summary>
        
/// 根據App對象,添加一個Excel Sheet對象
        
/// </summary>
        static public Excel._Workbook AddSheetPage(Excel._Application spExcelApp)
        {
            
if (spExcelApp == nullreturn null;
            
return spExcelApp.Workbooks.Add(System.Reflection.Missing.Value);
        }



        
/// <summary>
        
/// 核心方法,將一個dt轉換成一個數組對象
        
/// </summary>
        static public string[,] GetRangeDataArr(DataTable dt)
        {
            
if (dt == nullreturn null;
            
int iRow = dt.Rows.Count;
            
if (iRow <= 0return null;
            
int iColumn = dt.Columns.Count;
            
if (iColumn <= 0return null;

            
string[,] arrData = new string[iRow, iColumn];   //[row,col]
            for (int j = 0; j < iColumn; j++)
            {
                
for (int i = 0; i < iRow; i++)
                {
                    arrData[i, j] 
= dt.Rows[i][j].ToString().Trim();

                }

            }
            
return arrData;
        }




        
/// <summary>
        
/// 關閉指定薄
        
/// </summary>
        static public bool SaveAs(Excel._Workbook pBook,
            
string strFilePath
            )
        {
            pBook.SaveCopyAs(strFilePath);
            
return true;
        }


        
/// <summary>
        
/// 關閉指定薄
        
/// </summary>
        static public bool CloseBook(Excel._Workbook pBook,
            
bool bSave
            )
        {
            
bool bS = bSave ? true : false;
            pBook.Close(bS, System.Reflection.Missing.Value, System.Reflection.Missing.Value);
            
return true;
        }

        
/// <summary>
        
/// 釋放Excel Book對象
        
/// </summary>
        static public bool ReleaseBook(Excel._Workbook pBook)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject((
object)pBook);
            pBook 
= null;
            
return true;
        }

        
/// <summary>
        
/// 釋放Excel Sheet對象
        
/// </summary>
        static public bool ReleaseSheet(Excel._Worksheet pWorkSheet)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject((
object)pWorkSheet);
            pWorkSheet 
= null;
            
return true;
        }


        
/// <summary>
        
/// 釋放Excel App對象
        
/// </summary>
        static public bool ReleaseExcelApp(Excel._Application pWorkApp)
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject((
object)pWorkApp);
            pWorkApp 
= null;
            
return true;
        }


        
//*****************************************************
        /// <summary>
        
/// 是否無效 列範圍(1,255) 行範圍(1,~)
        
/// </summary>
        static public bool Invalid(long nRow, long nCol)
        {
            
return (nCol < 1 || nCol > 255|| (nRow < 1 || nRow > 65536);
        }

        
/// <summary>
        
/// 計算頁面大小
        
/// </summary>
        public long GetPageSize(long nEndRow, long nBegRow)
        {
            
return nEndRow - nBegRow + 1;
        }



        
/// <summary>
        
/// 根據頁面號,頁面長度,偏移行號,返回新的座標
        
/// </summary>
        public bool MovePage(long nRow, long nPageSize, long nPageNo)
        {
            nRow 
+= nPageSize * (nPageNo - 1);
            
return true;
        }

    
#endregion
    }
}
發佈了38 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章