天天看點

DataGridView控件導出到Excel檔案

主要用了2種方式來實作。

1.格式不做限制,普通清單顯示

      /// <summary>   

     /// 常用方法,列之間加\t,一行一行輸出,此檔案其實是csv檔案,不過預設可以當成Excel打開。   

     /// </summary>   

     /// <remarks>   

     /// using System.IO;   

     /// </remarks>   

     /// <param name="dgv"></param>   

     private void DataGridViewToExcel(DataGridView dgv)

      {

         SaveFileDialog dlg = new SaveFileDialog();

         dlg.Filter = "Execl files (*.xls)|*.xls";

         dlg.FilterIndex = 0;

         dlg.RestoreDirectory = true;

         dlg.CreatePrompt = true;

         dlg.Title = "儲存為Excel檔案";

         if (dlg.ShowDialog() == DialogResult.OK)

          {

             Stream myStream;

             myStream = dlg.OpenFile();

             StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));

             string columnTitle = "";

             try

              {

                 //寫入列标題   

                 for (int i = 0; i < dgv.ColumnCount; i++)

                  {

                     if (i > 0)

                      {

                         columnTitle += "\t";

                     }

                     columnTitle += dgv.Columns[i].HeaderText;

                 }

                 sw.WriteLine(columnTitle);

                 //寫入列内容   

                 for (int j = 0; j < dgv.Rows.Count; j++)

                  {

                     string columnValue = "";

                     for (int k = 0; k < dgv.Columns.Count; k++)

                      {

                         if (k > 0)

                          {

                             columnValue += "\t";

                         }

                         if (dgv.Rows[j].Cells[k].Value == null)

                             columnValue += "";

                         else

                             columnValue += dgv.Rows[j].Cells[k].Value.ToString().Trim();

                     }

                     sw.WriteLine(columnValue);

                 }

                 sw.Close();

                 myStream.Close();

             }

             catch (Exception e)

              {

                 MessageBox.Show(e.ToString());

             }

             finally

              {

                 sw.Close();

                 myStream.Close();

             }

         }

     }

對于複雜的,對于導出的excel有格式限制,可以考慮用Excel模闆(XML支援)來實作。 

 /// <summary>

        /// 将DataGridView中的資料導入到Excel中

        /// </summary>

        /// <param name="dt">DataGridView</param>

        /// <param name="templatePath">模闆的路徑</param>

        /// <param name="excelName">導入Excel的路徑</param>

        /// <returns></returns>

        public static bool DataGridViewToExcel(DataGridView dg, string templatePath, string excelName)

        {

            bool result = true;

            XmlDocument xmlDoc = new XmlDocument();

            if (File.Exists(templatePath))

            {

                xmlDoc.Load(templatePath);

                XmlNode root = xmlDoc.SelectSingleNode(@"/*[local-name()='Workbook']/*[local-name()='Worksheet'][1]/*[local-name()='Table']");

                foreach (DataGridViewRow dgRow in dg.Rows)

                {

                    XmlElement row = xmlDoc.CreateElement("", "Row", "urn:schemas-microsoft-com:office:spreadsheet");

                    row.SetAttribute("AutoFitHeight", "urn:schemas-microsoft-com:office:spreadsheet", "0");

                    foreach (DataGridViewColumn dgcol in dg.Columns)

                    {

                        if (dgcol.Visible && dgcol.IsDataBound && dgcol.GetType().Name == "DataGridViewTextBoxColumn")

                        {

                            XmlElement cell = xmlDoc.CreateElement("", "Cell", "urn:schemas-microsoft-com:office:spreadsheet");

                            XmlElement data = xmlDoc.CreateElement("", "Data", "urn:schemas-microsoft-com:office:spreadsheet");

                            data.SetAttribute("Type", "urn:schemas-microsoft-com:office:spreadsheet", "String");

                            data.InnerText = StringUility.ReturnFormatString(dgRow.Cells[dgcol.Name].Value);

                            cell.AppendChild(data);

                            row.AppendChild(cell);

                        }

                    }

                    //root.InsertBefore(row, root.LastChild);

                    root.AppendChild(row);

                }

                #region 添加合計行

                XmlElement totalRow = xmlDoc.CreateElement("", "Row", "urn:schemas-microsoft-com:office:spreadsheet");

                totalRow.SetAttribute("AutoFitHeight", "urn:schemas-microsoft-com:office:spreadsheet", "0");

                for (int i = 0; i < 2; i++)

                {

                    XmlElement cell = xmlDoc.CreateElement("", "Cell", "urn:schemas-microsoft-com:office:spreadsheet");

                    XmlElement data = xmlDoc.CreateElement("", "Data", "urn:schemas-microsoft-com:office:spreadsheet");

                    data.SetAttribute("Type", "urn:schemas-microsoft-com:office:spreadsheet", i == 0 ? "String" : "Number");

                    data.InnerText =(i==0?"合計":dg.Rows.Count.ToString());

                    cell.AppendChild(data);

                    totalRow.AppendChild(cell);

                }

                root.AppendChild(totalRow);

                #endregion

                XmlNode countnode = xmlDoc.SelectSingleNode(@"/*[local-name()='Workbook']/*[local-name()='Worksheet'][1]/*[local-name()='Table']");

                countnode.Attributes["ss:ExpandedRowCount"].Value = (Int32.Parse(countnode.Attributes["ss:ExpandedRowCount"].Value) + dg.Rows.Count+1).ToString();//标題+合計+資料

                xmlDoc.Save(excelName);

                result = true;

            }

            else

            {

                result = false;

            }

            return result;

        }

另外還有通過Microsoft Excel 11.0(12) Object Library,使用using Excel=Microsoft.Office.Interop.Excel調用CoM來實作。但必須有要求是安裝該軟體的應用程式必須裝Microsoft Office Excel才行。而且還應該設定運作該軟體的程式對COM有通路權限。

繼續閱讀