zoukankan      html  css  js  c++  java
  • [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;
            }
    
        }
    }
  • 相关阅读:
    同步、异步 与 阻塞、非阻塞
    【转】综合对比 Kafka、RabbitMQ、RocketMQ、ActiveMQ 四个分布式消息队列
    Kafka总结笔记
    SpringBoot笔记
    过滤器(Filter)和拦截器(Interceptor)的执行顺序和区别
    Java Lambda表达式
    腾讯云博客同步声明(非技术文)
    SpringBoot学习笔记(十七:异步调用)
    设计模式—— 十七:装饰器模式
    Java初级开发0608面试
  • 原文地址:https://www.cnblogs.com/Hsppl/p/2597668.html
Copyright © 2011-2022 走看看