ITPub博客

首页 > Linux操作系统 > Linux操作系统 > DataGridView导出Excel

DataGridView导出Excel

原创 Linux操作系统 作者:iSQlServer 时间:2009-08-14 11:01:16 0 删除 编辑

添加引用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/,如需转载,请注明出处,否则将追究法律责任。

下一篇: 初学SQL-交叉表
请登录后发表评论 登录
全部评论

注册时间:2008-10-17

  • 博文量
    1319
  • 访问量
    2074328