• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C#Excel的读写

原作者: [db:作者] 来自: [db:来源] 收藏 邀请
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Excel;

namespace Common
{
    class Tool
    {     /// <summary>
          /// 读excel,转换为DataTable
          /// </summary>
          /// <param name="path">excel存放的路径</param>
          /// <param name="sheetName">工作簿名称</param>
          /// <returns></returns>
        public static System.Data.DataTable ReadExcelToTable(string path, string sheetName)
        {
            try
            {
                bool IsCompatible = GetIsCompatible(path);
                string connstring;
                if (IsCompatible)
                {
                    connstring = "Provider=Microsoft.JET.OLEDB.4.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';"; //兼容模式
                }
                else
                {
                    connstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties='Excel 8.0;HDR=YES;IMEX=1';"; // Office 07及以上版本 不能出现多余的空格 而且分号注意
                }
                using (OleDbConnection conn = new OleDbConnection(connstring))
                {
                    conn.Open();
                    System.Data.DataTable sheetsName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" }); //得到所有sheet的名字                   
                    DataSet set = new DataSet();
                    string sql = string.Format("SELECT * FROM [{0}]", sheetName + "$"); //查询字符串
                    OleDbDataAdapter ada = new OleDbDataAdapter(sql, connstring);
                    ada.Fill(set, sheetName);
                    return set.Tables[sheetName];
                }
            }
            catch (Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
                return null;
            }
        }

        /// <summary>
        /// 判断是否为兼容模式
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static bool GetIsCompatible(string filePath)
        {
            string ext = Path.GetExtension(filePath);
            return new[] { ".xls", ".xlt" }.Count(e => e.Equals(ext, StringComparison.OrdinalIgnoreCase)) > 0;
        }
        public static string ExportDataTableToExcel(System.Data.DataTable dataTable, string filePath)
        {
            Application app;

            _Workbook wb;

            _Worksheet ws;

            object misValue = System.Reflection.Missing.Value;

            app = new Application();

            wb = app.Workbooks.Add(misValue);

            ws = (_Worksheet)wb.ActiveSheet;

            int rowIndex = 1;

            int colIndex = 0;

            //取得标题  
            foreach (DataColumn col in dataTable.Columns)
            {
                colIndex++;

                app.Cells[1, colIndex] = col.ColumnName;
            }

            //取得表格中的数据  
            foreach (DataRow row in dataTable.Rows)
            {
                rowIndex++;

                colIndex = 0;

                foreach (DataColumn col in dataTable.Columns)
                {
                    colIndex++;
                    app.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString().Trim();
                    //设置表格内容居中对齐  
                    //workSheet.get_Range(excel.Cells[rowIndex, colIndex], excel.Cells[rowIndex, colIndex]).HorizontalAlignment = Excel.XlVAlign.xlVAlignCenter;
                }
            }
            app.Visible = true;
            wb.SaveAs(filePath, XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
            dataTable = null;

            wb.Close(true, misValue, misValue);

            app.Quit();

            PublicMethod.Kill(app);//调用kill当前excel进程  

            releaseObject(ws);

            releaseObject(wb);

            releaseObject(app);

            if (!File.Exists(filePath))
            {
                return null;
            }
            return filePath;
        }
        public static bool ExportDataTableToExcel2(System.Data.DataTable dataTable, string filePath)
        {
            if (File.Exists(filePath))
            {
                System.Windows.Forms.MessageBox.Show(filePath + "已存在!", "提示");
                return false;
            }
            #region 初始化Excel表
            Excel.Application app = new Excel.Application();
            object MissingValue = Type.Missing;
            Excel.Workbook wb = app.Workbooks.Add(true);
            Excel.Worksheet ws = null;
            app.DisplayAlerts = false;
            app.AlertBeforeOverwriting = false;
            ws = (Excel.Worksheet)wb.Sheets["Sheet1"];
            #endregion

            #region 填充数据
            Object[,] dataArray = new Object[1 + dataTable.Rows.Count, dataTable.Columns.Count];
            for (int i = 0; i < dataTable.Columns.Count; i++)//填写列名
            {
                dataArray[0, i] = dataTable.Columns[i].ColumnName;

                for (int j = 0; j < dataTable.Rows.Count; j++)//填入数据
                {
                    dataArray[j + 1, i] = dataTable.Rows[j][i].ToString();
                }
            }
            #endregion

            Excel.Range range = ws.Range[ws.Cells[1, 1], ws.Cells[1 + dataTable.Rows.Count, dataTable.Columns.Count]];
            range.Value2 = dataArray;
            range.EntireColumn.AutoFit(); //自动设置列宽
            range.EntireRow.AutoFit(); //自动设置行高
            wb.Saved = true;
            // wb.SaveCopyAs(filePath);//保存
            wb.SaveAs(filePath);
            app.Quit();//关闭进程
            app = null;
            wb = null;
            ws = null;
            GC.Collect();

            if (File.Exists(filePath))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 释放COM组件对象
        /// </summary>
        /// <param name="obj"></param>
        private static void releaseObject(object obj)
        {
            try
            {
                System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
                obj = null;
            }
            catch
            {
                obj = null;
            }
            finally
            {
                GC.Collect();
            }
        }
        /// <summary>
        /// 关闭进程的内部类
        /// </summary>
        public class PublicMethod
        {
            [DllImport("User32.dll", CharSet = CharSet.Auto)]

            public static extern int GetWindowThreadProcessId(IntPtr hwnd, out int ID);

            public static void Kill(Microsoft.Office.Interop.Excel.Application excel)
            {
                //如果外层没有try catch方法这个地方需要抛异常。
                IntPtr t = new IntPtr(excel.Hwnd);

                int k = 0;

                GetWindowThreadProcessId(t, out k);

                System.Diagnostics.Process p = System.Diagnostics.Process.GetProcessById(k);

                p.Kill();
            }
        }
    }
}

 

         

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#对象的浅拷贝,深拷贝,序列化反序列化发布时间:2022-07-10
下一篇:
C#编程(五十一)----------链表发布时间:2022-07-10
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap