精华内容
下载资源
问答
  • winform 导入 导出 excel

    2018-06-26 22:11:00
    winform 导入 导出 excel https://blog.csdn.net/pp_fzp/article/details/51502233 posted @ 2018-06-26 22:11 Cgrain 阅读(...) 评论(...) 编辑 收藏 ...

    winform 导入 导出 excel

    https://blog.csdn.net/pp_fzp/article/details/51502233

    posted @ 2018-06-26 22:11 Cgrain 阅读( ...) 评论( ...) 编辑 收藏
    展开全文
  • C# winform 导入导出Excel

    热门讨论 2011-03-16 15:24:43
    C# winform操作Excel 读取Excel,写入Excel 导入导出Excel,比较适合新手
  • winForm导入导出EXCEL

    千次阅读 2011-08-05 10:00:44
    /// winForm程序导入导出EXCEL /// /// /// 使用方法: /// 读取EXCEL数据:ImportExcel(); /// 导出EXCEL:SaveAsExcel(system.data.datatable); /// public class ReadWriterExcel { /// /// 用oledb...
    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 WinExcel
    {
        /// <summary>
        /// winForm程序导入导出EXCEL
        /// </summary>
        /// <remarks>
        /// 使用方法:
        /// 读取EXCEL数据:ImportExcel();
        /// 导出EXCEL:SaveAsExcel(system.data.datatable);
        /// </remarks>
        public class ReadWriterExcel
        {
            /// <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里的数据导入到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
            /// </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;
            }
        }
    }
    



    展开全文
  • 帮客户做的一款导入Excel工具,并可通过导入的关键词进行筛选过滤,然后导出Excel。工具虽然简单,但是值得学习和借鉴。对winform学习Excel导入导出的初学者有很大帮助 开发工具是vs2017 .net版本为4.5
  • C# winform 导入导出excel

    2012-06-26 23:59:40
    //引用命名空间 using Microsoft.Office.Interop.Excel; //DataGridView 导出Excel  public static voidSaveAs(DataGridView gridView)  {  //导出到execl   try  {

    //引用命名空间   using Microsoft.Office.Interop.Excel;
    //DataGridView 导出到Excel
            public static voidSaveAs(DataGridView gridView)
            {
          //导出到execl   
                try
                {
                   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)
                   {
                     toolStripProgressBar1.Visible = true;
                       System.Reflection.Missing miss = System.Reflection.Missing.Value;
                       Microsoft.Office.Interop.Excel.ApplicationClass excel = newMicrosoft.Office.Interop.Excel.ApplicationClass();
                       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 = 1; i < gridView.ColumnCount; i++)
                       {

                           excel.Cells[1, i] = gridView.Columns[i].HeaderText.ToString();
                   
                       }
                     
                       //填充数据
                       for (int i = 0; i < gridView.RowCount; i++)
                       {

       //j也是从1开始  原因如上  每个人需求不一样
                           for (int j = 1; j < gridView.ColumnCount; j++)
                           {
                             
                                   if (gridView[j, i].Value.GetType() == typeof(string))
                                   {
                                       if (i < 9&&j==1)
                                       {
                                           string s="0"+gridView[j, i].Value.ToString().Trim();
                                           excel.Cells[i + 2, j] = "'" +s;
                                           continue;
                                       }
                                              excel.Cells[i + 2, j] = "'" + gridView[j,i].Value.ToString();               
                                 
                  
                                   }
                                   else
                                   {
                                       excel.Cells[i + 2, j ] = gridView[j, i].Value.ToString();
                                   }
                             

                             
                           }
                           toolStripProgressBar1.Value += 100 / gridView.RowCount;
                       }
                   
                       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, "错误提示");
                }

           }

    //获得当前你选择的Excel Sheet的所有名字

        public static string[] GetExcelSheetNames(string filePath)
            {

               Excel.ApplicationClass excelApp = new Excel.ApplicationClass();
               Excel.Workbooks wbs = excelApp.Workbooks;
               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);
                intcount=wb.Worksheets.Count;
               string[]names=new string[count];
                for (int i =1; i <= count; i++)
                {
                   names[i-1]=((Excel.Worksheet)wb.Worksheets[i]).Name;
                }
                returnnames;
            }

    //Excel导入到数据库Access中

    //filePath  你的Excel文件路径

      public static bool Import(string filePath)
            {
                try
                {

                       //Excel就好比一个数据源一般使用

                   string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "DataSource=" + filePath + ";" + "Extended Properties=Excel8.0;";

                   OleDbConnection con = new OleDbConnection(strConn);
                   con.Open();
                   string[] names = GetExcelSheetNames(filePath);
                   if (names.Length > 0)
                   {
                       foreach (string name in names)
                       {
                           OleDbCommand cmd = con.CreateCommand();
                           cmd.CommandText = string.Format(" select * from [{0}$]", name);//[sheetName$]要如此格式
                           OleDbDataReader odr = cmd.ExecuteReader();

                           while (odr.Read())
                           {

                               if (odr[0].ToString()== "序号")//过滤列头  按你的实际Excel文件
                                   continue;
                               Add(odr[1].ToString(), odr[2].ToString(), odr[3].ToString());//数据库添加操作

                           }
                           odr.Close();
                       }
                   }
                   return true;
                }
                catch(Exception)
                {
                   return false;
                }
                
            }


    我用了你的这些代码 但是有两个问题要问下 具体情况如下:
    public static bool Import(string filePath)
    {
    try
    {

    //Excel就好比一个数据源一般使用

    string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "DataSource=" + filePath + ";" + "Extended Properties=Excel8.0;";

    OleDbConnection con = new OleDbConnection(strConn);
    con.Open();
    string[] names = ExportToExcel.GetExcelSheetNames(filePath);
    if (names.Length > 0)
    {
    foreach (string name in names)
    {
    OleDbCommand cmd = con.CreateCommand();
    cmd.CommandText = string.Format(" select * from [{0}$]",name);//[sheetName$]要如此格式
    OleDbDataReader odr = cmd.ExecuteReader();

    while (odr.Read())
    {

    if (odr[0].ToString() == "序号")//过滤列头 按你的实际Excel文件
    continue;
    Add(odr[1].ToString(), odr[2].ToString(), odr[3].ToString());//数据库添加操作

    }
    odr.Close();
    }
    }
    return true;
    }
    catch (Exception)
    {
    return false;
    }

    }


    这个类中有提示 
    当前上下文中不存在“ExportToExcel”
    当前上下文中不存在“Add”


    有时间的时候能帮我看看问题出在什么地方吗?谢谢了啊!!

    @caopan
    ExportToExcel是自定义类和Add方法是自定义的方法 


    展开全文
  • C#,Winform,DatagridView,最详尽的导入导出数据到Excel
  • 1.在win7 64位和32位下对excel文件能正常导入导出,但是部署到XP系统下导入时会提示无法打开数据库,但是添加操作却是正常的(导入和添加调用的是一个方法)。 2.导出操作在win7也下能正常使用,部署到XP上之后我...
  • winform导入导出excel

    2013-09-18 11:12:07
    winform中数据导入导出excel,里面包含源代码
  • 2、最重要的是可以学会导入导出合并单元格的思想,本实例代码可能会对您的需求有出入,但重要的是思想; 3、学会如何使用Newtonsoft.Json.dll动态链接库,会使用JsonConvert.*生成和解析数据; 4、学会简单的使用...
  • //获取使用的excel 的版本号 if (Convert.ToDouble(Version) )//You use Excel 97-2003 { FormatNum = -4143; } else//you use excel 2007 or later { FormatNum = 56; } workbook.SaveAs(filePath, FormatNum);

    https://www.cnblogs.com/sun1630/p/5534754.html

    修改部分(根据使用的excel版本,生成excel):

    string Version;//excel版本号
                    int FormatNum;//保存excel文件的格式
                    Version = m_xlApp.Version;//获取使用的excel 的版本号
                    if (Convert.ToDouble(Version) < 12)//You use Excel 97-2003
                    {
                        FormatNum = -4143;
                    }
                    else//you use excel 2007 or later
                    {
                        FormatNum = 56;
                    }
                    workbook.SaveAs(filePath, FormatNum);
    
    展开全文
  • 主要为大家详细介绍了C# Winform实现导入导出Excel文件,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
  • C# winform Excel导入导出类,可以导出Excel,可以导入excel。支持07以上或以下版本,需要引用com组件里的microsoft excel,不需要安装其他插件。
  • C#数据库数据导入导出系列之四 WinForm数据库导入导出Excel 在日常的项目中,Excel,Word,txt等格式的数据导入到数据库中是很常见的,我在这里做一下总结 这里将分为Asp.net导入Sql Server,Oracle数据库和...
  • 之前网上有人分享的c# winform ListView导出Excel(2017),发现将代码应用到项目里面导出的Excel总是会出现 双引号和制表符号,自己在网上看到有人用npoi导出Excel,结合之前的代码进行改造成这个。文件扩展名使用 ...
  • winform 导出 Excel

    千次阅读 热门讨论 2019-03-01 14:51:16
    本篇博客将介绍「winform 导出 Excel」或「~~VS2017 导出 Excel~~ 」又或「C# 导出 Excel」又或「.Net 导出 Excel」的常用的两种方式以及简单分享其他方式(能力原因,已经尽力,用词还是可能不当)。
  • Winform 导入导出方法

    2016-05-27 15:20:00
    导出时:引用 using Excel = Microsoft.Office.Interop.Excel; #region 读取excel //打开方法 public DataTable ExceltoDataSet(string path) { string strConn = "Provider...
  • C#_WinFormExcel导入导出,文档中有导入导出的源代码
  • C#中,winform中dataGridView导入EXCLE数据,或从dataGridView中导出Excel表格。可以指定导入路径或导出路径。
  • winForm c#导出Excel

    千次阅读 2009-01-12 17:06:00
    参考网上的方法修改,1000条记录导出只要3S(1GRDM,C2.8CPU).1.项目添加excel对象类库的引用,Microsoft Excel 11.0 object library(不同版本的Excel,类库不同,这是2003的) 2.代码1 //-***************获取要...
  • #region 导入、导出方法 ... /// DataGridView导出Excel(工作区域保护) /// /// Excel文件中的标题 /// 文件名 /// 不需要保护的列明 /// 返回信息,空为成功 public string ExportExcel
  • 在asp.net中导出Execl有两种方法.一种是将导出的文件存放在服务器某个文件夹下面.一种是将文件直接将文件输出流写给浏览器
  • C# WinFormExcel导入导出

    千次阅读 2014-11-10 22:32:11
    C# WinFormExcel导入导出 //引用命名空间 using Microsoft.Office.Interop.Excel; //DataGridView 导出到Excel  public static void SaveAs(DataGridView gridView)  {  //导出到execl   
  • winform高效导出Excel带格式设置

    千次阅读 2011-03-08 11:34:00
    参考网上的方法修改,1000条记录导出只要3S(1GRDM,C2.8CPU). 1.项目添加excel对象类库的引用,Microsoft Excel 11.0 object library(不同版本的Excel,类库不同,这是2003的) 2.代码  1//-**************...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 1,948
精华内容 779
关键字:

winform导入导出excel