C# WinForm下Excel导入导出

//引用命名空间   using Microsoft.Office.Interop.Excel;
//DataGridView 导出到Excel
        public static void SaveAs(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 = new Microsoft.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);
            int count=wb.Worksheets.Count;
            string[]names=new string[count];
            for (int i = 1; i <= count; i++)
            {
                names[i-1]=((Excel.Worksheet)wb.Worksheets[i]).Name;
            }
            return names;
        }
 
//Excel导入到数据库Access中
 
//filePath  你的Excel文件路径
   public static bool Import(string filePath)
        {
            try
            {
                    //Excel就好比一个数据源一般使用
                string strConn = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + filePath + ";" + "Extended Properties=Excel 8.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;
            }
            
        }


相关推荐

评论

  1. #2

    木庄网络博客(2016/10/28 11:41:03)
    不错的网站主题,看着相当舒服

  2. #1

    木庄网络博客(2016/10/14 21:02:39)
    博客做得好漂亮哦!