[C#]Excel操作类

using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Runtime.InteropServices;
using System.Data.OleDb;
using System.IO;
using System.Windows.Forms;
using System.Collections;
using System.Drawing;
using Microsoft.Office.Interop.Excel;
using DevExpress.XtraGrid.Views.Grid;

namespace HDSafetyClient.Function
{
    /// <summary>
    /// winForm程序导入导出EXCEL
    /// </summary>
    /// <remarks>
    /// 使用方法:
    /// 读取EXCEL数据:ImportExcel();
    /// 导出EXCEL:SaveAsExcel(system.data.datatable);
    /// </remarks>
    public class ExcelHelper
    {
        /// <summary>
        /// 用oledb方式读取excel到datatable
        /// </summary>
        /// <remarks></remarks>
        /// <param name="strPath">文件存放路径</param>
        /// <returns></returns>
        private static System.Data.DataTable GetData(string strPath)
        {
            System.Data.DataTable dt = new System.Data.DataTable();
            try
            {
                string strCon = "Provider=Microsoft.Jet.OLEDB.4.0;"   "Data Source="   strPath   ";"   "Extended Properties=Excel 8.0;";
                string strSheetName = "";
                using (OleDbConnection con = new OleDbConnection(strCon))
                {
                    con.Open();
                    System.Data.DataTable dtTemp = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                    strSheetName = dtTemp.Rows[0][2].ToString().Trim();
                }
                String strCmd = "select * from ["   strSheetName   "]";
                OleDbDataAdapter cmd = new OleDbDataAdapter(strCmd, strCon);
                cmd.Fill(dt);
            }
            catch (Exception) { throw; }
            return dt;
        }
        /// <summary>
        /// winform程序,点击程序上的按钮,找到Excel文件,打开后把这个Excel里的数据导入到oracle数据库里 
        /// </summary>
        /// <param name="file">文件路径</param>
        /// <returns></returns>
        public static DataSet ImportExcel(string file)
        {
            FileInfo fileInfo = new FileInfo(file);
            if (!fileInfo.Exists)
                return null;

            string strConn = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source="   file   ";Extended Properties='Excel 8.0;HDR=NO;IMEX=1'";
            OleDbConnection objConn = new OleDbConnection(strConn);
            DataSet dsExcel = new DataSet();
            try
            {
                objConn.Open();
                string strSql = "select * from  [Sheet1$]";
                OleDbDataAdapter odbcExcelDataAdapter = new OleDbDataAdapter(strSql, objConn);
                odbcExcelDataAdapter.Fill(dsExcel);
                return dsExcel;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>--导出到Excel--
        /// Guo Jin
        /// </summary>
        /// <param name="dtExcel">数据源</param>
        /// <param name="filePath">导出文件路径</param>
        /// <param name="colsName">要导出的字段</param>
        /// <param name="sheetName">工作簿名称</param>
        /// <returns></returns>
        public static int SaveAsExcel(System.Data.DataTable dtExcel, string filePath, Hashtable colsName, string sheetName)
        {
            int result = 0;
            if (filePath.Length != 0)
            {
                //导出到execl  
                System.Reflection.Missing miss = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Excel.ApplicationClass excel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                try
                {
                    excel.Application.Workbooks.Add(true);
                    excel.Visible = false;//若是true,则在导出的时候会显示Excel界面。
                    if (excel == null)
                    {
                        result = 2;
                        return result;
                    }
                    Microsoft.Office.Interop.Excel.Workbooks books = (Microsoft.Office.Interop.Excel.Workbooks)excel.Workbooks;
                    Microsoft.Office.Interop.Excel.Workbook book = (Microsoft.Office.Interop.Excel.Workbook)(books.Add(miss));
                    Microsoft.Office.Interop.Excel.Worksheet sheet = (Microsoft.Office.Interop.Excel.Worksheet)book.ActiveSheet;
                    sheet.Name = sheetName;

                    //生成列名称 
                    excel.Cells[1, 1] = "序号";
                    int ind = 0;
                    foreach (System.Collections.DictionaryEntry obj in colsName)
                    {
                        excel.Cells[1, ind   2] = obj.Value.ToString();//列名
                        ind  ;
                    }

                    Microsoft.Office.Interop.Excel.Range range = excel.get_Range(excel.Cells[1, 1], excel.Cells[1, ind   1]);
                    range.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb();
                    range.Borders.LineStyle = 1;     //设置单元格边框的粗细

                    //range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());     //给单元格加边框
                    //range.Interior.ColorIndex = 39;     //填充颜色为淡紫色

                    //填充数据 行
                    for (int i = 0; i < dtExcel.Rows.Count; i  )
                    {
                        //
                        int col = 0;

                        foreach (System.Collections.DictionaryEntry obj in colsName)
                        {
                            for (int j = 0; j < dtExcel.Columns.Count; j  )
                            {
                                if (obj.Key.Equals(dtExcel.Columns[j].Caption))
                                {
                                    if (dtExcel.Rows[i][j].ToString().GetType() == typeof(string))
                                    {
                                        excel.Cells[i   2, col   2] = "'"   dtExcel.Rows[i][j].ToString().Trim();
                                    }
                                    else
                                    {
                                        excel.Cells[i   2, col   2] = dtExcel.Rows[i][j].ToString().Trim();
                                    }
                                    col  ;
                                    break;
                                }
                            }
                        }
                        //序号
                        excel.Cells[i   2, 1] = "'"   (i   1);
                    }

                    sheet.SaveAs(filePath, miss, miss, miss, miss, miss, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, miss, miss, miss);
                    book.Close(false, miss, miss);
                    books.Close();
                    excel.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(book);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(books);
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(excel);

                    GC.Collect();

                    System.Diagnostics.Process.Start(filePath);
                    result = 1;
                }
                catch (Exception)
                {
                    result = 3;
                }
                finally
                {
                    //excel.Quit();
                    //KillSpecialExcel(excel);
                }
            }
            else
                result = 0;
            return result;
        }

        /// <summary>--从DataGridView中把数据导出--
        /// Guo Jin
        /// </summary>
        /// <param name="dgv"></param>
        /// <param name="isShowExcle">是否显示excel</param>
        /// <returns></returns>
        public static bool DataGridviewShowToExcel(GridView dgv, bool isShowExcle)
        {
            if (dgv.RowCount == 0)
                return false;
            //建立Excel对象 
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(true);
            excel.Visible = isShowExcle;
            //生成字段名称 
            for (int i = 0; i < dgv.Columns.Count; i  )
            {
                if (dgv.Columns[i].Caption != "主键" && dgv.Columns[i].Caption != "查看" && dgv.Columns[i].Caption != "修改" && dgv.Columns[i].Caption != "删除" && dgv.Columns[i].Caption != "11111")
                    excel.Cells[1, i   1] = dgv.Columns[i].Caption;
            }
            //填充数据 
            for (int i = 0; i < dgv.RowCount; i  )
            {
                for (int j = 0; j < dgv.Columns.Count; j  )
                {
                    if (dgv.Columns[j].Caption != "主键" && dgv.Columns[j].Caption != "查看" && dgv.Columns[j].Caption != "修改" && dgv.Columns[j].Caption != "删除" && dgv.Columns[j].Caption != "11111")
                        excel.Cells[i   2, j   1] = dgv.GetRowCellValue(i, dgv.Columns[j]).ToString();
                }
            }
            return true;
        }

        public static bool TabPageShowToExcel(TabPage tPage, bool isShowExcle)
        {
            //建立Excel对象 
            Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
            excel.Application.Workbooks.Add(true);
            excel.Visible = isShowExcle;
            //生成字段名称 
            excel.Cells[1, 1] = "企业日常检查记录";
            int rowInd = 1;
            foreach (LinkLabel lkb in tPage.Controls)
            {
                rowInd  ;
                excel.Cells[rowInd, 1] = lkb.Text;
            }
            return true;
        }

        //获得当前你选择的Excel Sheet的所有名字
        private string[] GetExcelSheetNames(string filePath)
        {
            Microsoft.Office.Interop.Excel.ApplicationClass excelApp = new Microsoft.Office.Interop.Excel.ApplicationClass();
            Microsoft.Office.Interop.Excel.Workbooks wbs = excelApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook wb = wbs.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);
            int count = wb.Worksheets.Count;
            string[] names = new string[count];
            for (int i = 1; i <= count; i  )
            {
                names[i - 1] = ((Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets[i]).Name;
            }
            return names;
        }

        private void ReleaseExcel(Microsoft.Office.Interop.Excel.Application m_objExcel)
        {
            m_objExcel.Quit();

            //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objExcel);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objBooks);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)m_objBook);
            //System.Runtime.InteropServices.Marshal.ReleaseComObject((object)sheet);

            //sheet = null;
            //m_objBook = null;
            //m_objBooks = null;
            m_objExcel = null;

            GC.Collect(0);
        }

        #region KillAllExcel 停止EXCEL进程
        private bool KillAllExcel(Microsoft.Office.Interop.Excel.Application m_objExcel)
        {
            try
            {
                if (m_objExcel != null) // isRunning是判断xlApp是怎么启动的flag. 
                {
                    m_objExcel.Quit();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(m_objExcel);
                    //释放COM组件,其实就是将其引用计数减1 
                    //System.Diagnostics.Process theProc; 
                    foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
                    {
                        //先关闭图形窗口。如果关闭失败...有的时候在状态里看不到图形窗口的excel了, 
                        //但是在进程里仍然有EXCEL.EXE的进程存在,那么就需要杀掉它:p 
                        if (theProc.CloseMainWindow() == false)
                        {
                            theProc.Kill();
                        }
                    }
                    m_objExcel = null;
                    return true;
                }
            }
            catch
            {
                return false;
            }
            return true;
        }
        #endregion

        #region Kill Special Excel Process
        [DllImport("User32.dll", CharSet = CharSet.Auto)]
        static extern int GetWindowThreadProcessId(IntPtr hWnd, out int lpdwProcessId);

        private static void KillSpecialExcel(Microsoft.Office.Interop.Excel.Application m_objExcel)
        {
            try
            {
                if (m_objExcel != null)
                {
                    int lpdwProcessId;
                    GetWindowThreadProcessId(new IntPtr(m_objExcel.Hwnd), out lpdwProcessId);
                    System.Diagnostics.Process.GetProcessById(lpdwProcessId).Kill();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Delete Excel Process Error:"   ex.Message);
            }
        }
        #endregion

        /// <summary>
        /// 导入EXCEL
        /// </summary>
        /// <returns> System.Data.DataTable</returns>
        public static System.Data.DataTable ImportExcel()
             {
            System.Data.DataTable dt;
            OpenFileDialog openfile = new OpenFileDialog();
            openfile.Filter = "Excel表格文件(*.xls)|*.xls";
            if (openfile.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    dt = GetData(openfile.FileName);//获得Excel
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                dt = null;
            }
            return dt;
        }

        public static System.Data.DataTable ImportExcel1(string file)
        {
            System.Data.DataTable dt;
            try
            {
                dt = GetData(file);

            }
            catch (Exception ex)
            {
                throw ex;
            }
            return dt;
        }

    }
}

转载于:https://www.cnblogs.com/Hsppl/archive/2012/07/18/2597668.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值