c# excel的導入以及導出到datagridview,兼容 2003和2007版本的excel

    首先確定pc裝的excel是什麼版本,如果是1997-2003那麼導入的dll就是Microsoft Excel 11.0 Object Library,否則會報錯,如果是2007或者2010以上的excel,導入的dll就是Microsoft Excel 12.0 Object Library。以下代碼可以直接使用,如果pc沒有裝過excel,那是無法使用的,那些用流文件生成的excel是假的,不建議使用,因爲高版本excel(大於2007)打開就會報錯格式問題。

 

using Microsoft.Office.Interop.Excel;
 

   /// <summary>
        /// 將制定sheet中的數據導出到datatable中
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        internal System.Data.DataTable ImportExcel(string filePath)

        {
            DataSet ds=null;
            System.Data.DataTable dt=null;
            Microsoft.Office.Interop.Excel.Application excel=new Microsoft.Office.Interop.Excel.Application();
            Microsoft.Office.Interop.Excel.Workbook workbook=null;
            Microsoft.Office.Interop.Excel.Worksheet worksheet=null;
            Microsoft.Office.Interop.Excel.Sheets sheets=null;
            Microsoft.Office.Interop.Excel.Range range=null;
            object missing=System.Reflection.Missing.Value;
            try
            {
                if (excel == null)
                {
                    return null;
                }
                //打開Excel文件
                workbook = excel.Workbooks.Open(
                filePath, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
                //獲取所有的sheet表
                sheets = workbook.Worksheets;
                ds = new DataSet();
                for (int i = 1; i <= sheets.Count; i++)
                {
                    //獲取第一個表
                    worksheet = (Microsoft.Office.Interop.Excel.Worksheet)sheets.get_Item(i);
                    int rowCount = worksheet.UsedRange.Rows.Count;
                    int colCount = worksheet.UsedRange.Columns.Count;
                    int rowIndex = 1;
                    int colIndex = 1;
                    DataColumn dc;
                    dt = new System.Data.DataTable();
                    dt.TableName = "table" + i.ToString();
                    //讀取列名
                    for (int j = 0; j < colCount; j++)
                    {
                        range = worksheet.Cells[rowIndex, colIndex + j];
                        dc = new DataColumn();
                        dc.DataType = Type.GetType("System.String");
                        dc.ColumnName = range.Text.ToString().Trim();
                        //添加列
                        dt.Columns.Add(dc);
                    }
                    //讀取行數據
                    for (int k = 1; k < rowCount; k++)
                    {
                        DataRow dr = dt.NewRow();
                        for (int l = 0; l < colCount; l++)
                        {
                            range = worksheet.Cells[rowIndex + k, colIndex + l];
                            dr[l] = range.Text.ToString();
                        }
                        //dt.Tables.Add(dr);
                        dt.Rows.Add(dr);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
            }
            finally
            {
                workbook.Close();
                excel.Quit();
                Marshal.ReleaseComObject(worksheet);
                Marshal.ReleaseComObject(workbook);
                Marshal.ReleaseComObject(excel);
                worksheet=null;
                workbook=null;
                excel=null;
                GC.Collect();
            }
         //   return ds;
            return dt;
        }

 

        /// <summary>
        /// 將datatable導出到excel
        /// </summary>
        /// <param name="tb1"></param>
        /// <returns></returns>
        internal bool  ExportToExecl(System.Data.DataTable tb1)
        {
          
                System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog();
                sfd.DefaultExt = "xlsx";
                sfd.Filter = "Excel文件(*.xlsx)|*.xlsx";
                if (sfd.ShowDialog() != DialogResult.OK)
                {
                    // DoExport(dgv, sfd.FileName);
                    return false ;
                }
                  //  ExportForDataGridview(dt, sfd.FileName, false);
                 Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
             try
                {
                    if (app == null)
                    {
                        return false;
                    }

                    app.Visible = false;//不打開excel
                    Workbooks workbooks = app.Workbooks;
                    _Workbook workbook = workbooks.Add(XlWBATemplate.xlWBATWorksheet);
                    Sheets sheets = workbook.Worksheets;
                    _Worksheet worksheet = (_Worksheet)sheets.get_Item(1);
                    if (worksheet == null)
                    {
                        return false;
                    }
                    string sLen = "";
                 
                    //取得最後一列列名
                    char H = (char)(64 +  tb1.Columns.Count  / 26);
                    char L = (char)(64 +   tb1.Columns.Count  % 26);
                    if (  tb1.Columns.Count  < 26)
                    {
                        sLen = L.ToString();
                    }
                    else
                    {
                        sLen = H.ToString() + L.ToString();
                    }

                    //標題
                    string sTmp = sLen + "1";
                    Range ranCaption = worksheet.get_Range(sTmp, "A1");
                    string[] asCaption = new string[  tb1.Columns.Count ];
                    for (int i = 0; i <   tb1.Columns.Count ; i++)//生成列名
                    {
                        asCaption[i] =  tb1.Columns[i].ColumnName;
                    }
                    ranCaption.Value2 = asCaption;
              
                    //數據
                    object[] obj = new object[tb1.Rows.Count];
                    for (int r = 0; r < tb1.Rows.Count ; r++)//輪詢行
                    {
                        if (r == 18)
                        { }
                        for (int l = 0; l <tb1.Columns.Count; l++)//填充列的值
                        {
                            if( tb1.Columns[l].DataType == typeof(DateTime))
                            {
                                obj[l] = tb1.Rows[r][l].ToString();
                            }
                            else
                            {
                                obj[l] = tb1.Rows[r][l];
                            }
                        }
                        string cell1 = sLen + ((int)(r + 2)).ToString();
                        string cell2 = "A" + ((int)(r + 2)).ToString();
                        Range ran = worksheet.get_Range(cell1, cell2);
                        ran.Value2 = obj;
                    }
                //保存
                if (!File.Exists( sfd.FileName))
                {
                     FileStream fs = File.Create( sfd.FileName);//創建文件
                    fs.Close();
                }
               
                workbook.SaveCopyAs( sfd.FileName);
                workbook.Saved = true;
            }
        catch(Exception ex)
             {
                 MessageBox.Show(ex.ToString());
                 return false;
            }
        finally
            {
                //關閉
                app.UserControl = false;
                app.Quit();
            }
            return true;

        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章