DataGridView匯出Excel

iSQlServer發表於2009-08-14

新增引用GemBox.ExcelLite.dll

==============================================================================================

參考程式碼

==============================================================================================

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using GemBox.ExcelLite;//引用GemBox.ExcelLite

namespace Excel{
    public partial class frmExcel : Form
    {
        public frmExcel()
        {
            InitializeComponent();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            if (txtName.Text != "")
            {
                try
                {
                    ExcelFile excelFile = new ExcelFile();
                    ExcelWorksheet sheet = excelFile.Worksheets.Add(txtName.Text.Trim());

                    int columns = dgvInfo.Columns.Count;
                    int rows = dgvInfo.Rows.Count;

                    for (int j = 0; j < columns; j++)
                    {
                        sheet.Cells[0, j].Value = dgvInfo.Columns[j].HeaderText;
                    }

                    for (int i = 1; i <= rows; i++)
                    {
                        for (int j = 0; j < columns; j++)
                        {
                            sheet.Cells[i, j].Value = dgvInfo[j, i - 1].Value;
                        }
                    }
                    string strName = string.Format("http://www.cnblogs.com/../{0}.xls", txtName.Text.Trim());
                    excelFile.SaveXls(strName);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    MessageBox.Show("匯出成功", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
            }
            else
            {
                MessageBox.Show("請輸入名稱!", "系統提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/16436858/viewspace-612306/,如需轉載,請註明出處,否則將追究法律責任。

相關文章