Excle导入到出。。。

1 篇文章 0 订阅
 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.OleDb;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace ExcelInputAndOutPut
{
    /// <summary>
    /// winForm程序导入导出EXCEL
    /// </summary>
    /// <remarks>
    /// 使用方法:
    /// 读取EXCEL数据:ImportExcel();
    /// 导出EXCEL:SaveAsExcel(system.data.datatable);
    /// </remarks>
    public class ExcelInputAndOutPut
    {
        /// <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 ex)
            {
                MessageBox.Show(ex.Message);
            }
            return dt;
        }
        /// <summary>
        /// winform程序,点击程序上的按钮,找到Excel文件,打开后把这个Excel里的数据导入到sqlserver数据库里
        /// </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
        /// </summary>
        /// <param name="dtExcel">数据源</param>
        public static void SaveAsExcel(System.Data.DataTable dtExcel)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "导出Excel (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出文件保存路径";
            saveFileDialog.ShowDialog();
            string strName = saveFileDialog.FileName;
            if (strName.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)
                    {
                        MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                    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 = "test";

                    int m = 0, n = 0;
                    //生成列名称   这里i是从1开始的 因为我第0列是个隐藏列ID  没必要写进去
                    for (int i = 0; i < dtExcel.Columns.Count; i++)
                    {
                        excel.Cells[1, i + 1] = dtExcel.Columns[i].Caption.ToString();
                    }

                    //填充数据
                    for (int i = 0; i < dtExcel.Rows.Count; i++)
                    {
                        //j也是从1开始  原因如上  每个人需求不一样
                        for (int j = 0; j < dtExcel.Columns.Count; j++)
                        {
                            if (dtExcel.Rows[i][j].ToString().GetType() == typeof(string))
                            {
                                excel.Cells[i + 2, j + 1] = "'" + dtExcel.Rows[i][j].ToString().Trim();
                            }
                            else
                            {
                                excel.Cells[i + 2, j + 1] = dtExcel.Rows[i][j].ToString().Trim();
                            }
                        }
                    }

                    sheet.SaveAs(strName, 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();
                    MessageBox.Show("数据已经成功导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    //toolStripProgressBar1.Value = 0;
                    System.Diagnostics.Process.Start(strName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误提示");
                }
                finally
                {
                    //excel.Quit();
                    KillSpecialExcel(excel);

                }
            }
        }
        //获得当前你选择的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();
            if (openfile.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    dt = GetData(openfile.FileName);//获得Excel
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }
            else
            {
                dt = null;
            }
            return dt;
        }
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值