我想在exportbutton_Click中填加一些代码,实现把datagridview显示的数据导入到excel
下面是我的程序:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using Microsoft.Office.Interop.Excel;namespace SMLReportSystem
{
    partial class MAERSK : Form
    {
        public MAERSK(SMLReportSystem.SMLReport parent)
        {
            InitializeComponent();            this.MdiParent = parent;
        }        private void fillToolStripButton_Click(object sender, EventArgs e)
        {
            try
            {
                this.pr_MAERSKTableAdapter.Fill(this.sMLRPTDataSet.pr_MAERSK, new System.Nullable<System.DateTime>(((System.DateTime)(System.Convert.ChangeType(dateTimePickerStart.Text, typeof(System.DateTime))))), new System.Nullable<System.DateTime>(((System.DateTime)(System.Convert.ChangeType(dateTimePickerEnd.Text, typeof(System.DateTime))))));
            }
            catch (System.Exception ex)
            {
                System.Windows.Forms.MessageBox.Show(ex.Message);
            }
        }        private void exportbutton_Click(object sender, EventArgs e)
        {        }
    }
}
小妹初级,分少,希望大家不要嫌弃

解决方案 »

  1.   

    可以看看这里
    http://blog.csdn.net/simonllf/archive/2006/12/13/1441672.aspx
      

  2.   

    simonllf 夺命刀剪脚   ,在下不才,刚刚学起,手写代码能力太差,参考不太明白这个.我就是想把代码都写在这个按钮里来实现功能,不知道可不可以.我在别的地方找了个代码
    private void ToExcel_Click(object sender, EventArgs e)
            {
                Microsoft.Office.Interop.Excel.ApplicationClass MyExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                MyExcel.Visible = true;
                if (MyExcel == null)
                {
                    MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                int rowcount = 0;
                int columncount = 0;
                MyExcel.Application.Workbooks.Add(true);
                columncount = this.show.ColumnCount;
                rowcount = this.show.RowCount;
                for (int m = 1; m < columncount; m++)
                {
                    MyExcel.Cells[1, m] = this.show.Columns[m-1].HeaderText;//去除show的编号列
                }
                for (int i = 0; i < rowcount; i++)
                {
                    for (int j = 1; j < columncount; j++)
                    {
                        MyExcel.Cells[i + 2, j] = Convert.ToString(this.show[j-1, i].Value);
                    }        }
    运行提示错误:“SMLReportSystem.MAERSK”并不包含“show”的定义
    我都不知道怎么声明"show"......希望大家多多帮忙,谢谢大家了!
      

  3.   


            private void button1_Click(object sender, EventArgs e)
            {
                System.Windows.Forms.SaveFileDialog saveFileDlg = new SaveFileDialog();
                saveFileDlg.FileName = "报废信息";//默认文件名
                saveFileDlg.DefaultExt = "xls";//默认后缀名
                saveFileDlg.Filter = "Excel文件 (*.xls)|*.xls";            if (saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    try
                    {
                        doExport(rollInfoDs1, saveFileDlg.FileName);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message, "系统管理", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            private void doExport(DataSet ds, string strExcelFileName)
            {
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                if (excel == null)
                    throw new Exception("无法启动Excel,可能您的计算机尚未安装Excel");
                int rowIndex = 1;
                int colIndex = 0;            excel.Application.Workbooks.Add(true);            System.Data.DataTable table = ds.Tables["ROLLINFO"];
                if (table != null && table.Rows.Count > 0)
                {
                    DataTable dataTableNew = new DataTable();
                    dataTableNew.Columns.Add("序号");
                    dataTableNew.Columns.Add("钢号");
                    dataTableNew.Columns.Add("现场编号");
                    for (int i = 0; i < table.Rows.Count; i++)
                    {
                        DataRow dr = dataTableNew.NewRow();
                        dr["序号"] = table.Rows[i]["XH"].ToString();
                        dr["钢号"] = table.Rows[i]["ROLL_ID"].ToString();
                        dr["现场编号"] = table.Rows[i]["ROLL_NUM"].ToString();
                        dataTableNew.Rows.Add(dr);
                    }                foreach (DataColumn col in dataTableNew.Columns)
                    {
                        colIndex++;
                        excel.Cells[1, colIndex] = col.ColumnName;
                    }
                    foreach (DataRow row in dataTableNew.Rows)
                    {
                        rowIndex++;
                        colIndex = 0;
                        foreach (DataColumn col in dataTableNew.Columns)
                        {
                            colIndex++;
                            excel.Rows.Cells[rowIndex, colIndex] = row[col.ColumnName].ToString();
                        }
                    }
                }
                
                excel.Visible = false;
                try
                {
                    excel.ActiveWorkbook.SaveAs(strExcelFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                excel.Quit();
                excel = null;            GC.Collect();//垃圾回收   
            }
      

  4.   

    hxq987 黄泉  ,先谢谢你了.小妹愚笨...理解不了代码,所以调试不成功.我只是想把经过查询后在datagridview里面显示出来的数据导入到EXCEL,望各位大国帮忙给说详细点,谢谢大家了
      

  5.   

    private void button1_Click(object sender, EventArgs e) 
            { 
                System.Windows.Forms.SaveFileDialog saveFileDlg = new SaveFileDialog(); 
                saveFileDlg.FileName = "报废信息";//默认文件名 
                saveFileDlg.DefaultExt = "xls";//默认后缀名 
                saveFileDlg.Filter = "Excel文件 (*.xls) ¦*.xls";             if (saveFileDlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) 
                { 
                    try 
                    { 
                        doExport(saveFileDlg.FileName); 
                    } 
                    catch (Exception ex) 
                    { 
                        MessageBox.Show(ex.Message, "系统管理", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
                    } 
                } 
            }         private void doExport(string strExcelFileName)
            {
                Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
                if (excel == null)
                    throw new Exception("无法启动Excel,可能您的计算机尚未安装Excel");
                int rowIndex = 1;
                int colIndex = 0;            excel.Application.Workbooks.Add(true);
                if (dataGridView1 != null && dataGridView1.Rows.Count > 0)
                {
                    for (int i = 0; i < dataGridView1.ColumnCount; i++)
                    {
                        colIndex++;
                        excel.Cells[1, colIndex] = dataGridView1.Columns[i].Name;
                    }
                    foreach (DataGridViewRow row in dataGridView1.Rows)
                    {
                        rowIndex++;
                        colIndex = 0;
                        foreach (DataGridViewColumn col in dataGridView1.Columns)
                        {
                            colIndex++;
                            excel.Rows.Cells[rowIndex, colIndex] = row.Cells[col.Name].Value != null ? row.Cells[col.Name].Value.ToString() : "";
                        }
                    }
                }            excel.Visible = false;
                try
                {
                    excel.ActiveWorkbook.SaveAs(strExcelFileName, Microsoft.Office.Interop.Excel.XlFileFormat.xlExcel9795, null, null, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, null, null, null, null, null);
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                excel.Quit();
                excel = null;            GC.Collect();//垃圾回收  
            }
      

  6.   

    我在网上找了段代码,贴到我的程序里运行后提示错误“SMLReportSystem.MAERSK”并不包含“show”的定义
    提供代码的网页上有注明show是datagridview类型的变量,可是我不知道怎么声明,希望大家给点帮助,谢谢大家了
    下面是我的程序的代码
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Data.SqlClient;
    using Microsoft.Office.Interop.Excel;namespace SMLReportSystem
    {
        partial class MAERSK : Form
        {
            public MAERSK(SMLReportSystem.SMLReport parent)
            {
                InitializeComponent();            this.MdiParent = parent;
            }        private void fillToolStripButton_Click(object sender, EventArgs e)
            {
                try
                {
                    this.pr_MAERSKTableAdapter.Fill(this.sMLRPTDataSet.pr_MAERSK, new System.Nullable<System.DateTime>(((System.DateTime)(System.Convert.ChangeType(dateTimePickerStart.Text, typeof(System.DateTime))))), new System.Nullable<System.DateTime>(((System.DateTime)(System.Convert.ChangeType(dateTimePickerEnd.Text, typeof(System.DateTime))))));
                }
                catch (System.Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.Message);
                }
            }        private void exportbutton_Click(object sender, EventArgs e)
            {
                Microsoft.Office.Interop.Excel.ApplicationClass MyExcel = new Microsoft.Office.Interop.Excel.ApplicationClass();
                MyExcel.Visible = true;
                if (MyExcel == null)
                {
                    MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                int rowcount = 0;
                int columncount = 0;
                MyExcel.Application.Workbooks.Add(true);
                columncount = this.show.ColumnCount;
                rowcount = this.show.RowCount;
                for (int m = 1; m < columncount; m++)
                {
                    MyExcel.Cells[1, m] = this.show.Columns[m - 1].HeaderText;//去除show的编号列
                }
                for (int i = 0; i < rowcount; i++)
                {
                    for (int j = 1; j < columncount; j++)
                    {
                        MyExcel.Cells[i + 2, j] = Convert.ToString(this.show[j - 1, i].Value);
                    }            }
            }
        }
    }
      

  7.   

    hxq987 黄泉  ,我的datagridview名字是pr_MAERSKDataGridView.您给的代码里的datagridview和datagridview1分别指的是什么哦,我是不是还需要在哪里声明一下啊?小妹先在这谢谢大哥您了
      

  8.   

    把dataGridView1改成你的pr_MAERSKDataGridView就可以了
      

  9.   

    错误 1 当前上下文中不存在名称“dataGridView” E:\BegVCSharp\SMLReport\SMLReportSystem\SMLReportSystem\MAERSK.cs 43 17 SMLReportSystem
    大国,它提示我这个怎么办啊?
      

  10.   

    我把dataGridView也改成pr_MAERSKDataGridView以后运行成功了,但是点击Export to Excel的时候提示
    应用程序中发生了无法处理的异常.如果单击继续应用程序将忽略此错误并尝试继续.如果单击退出应用程序将立即关闭.
    提供的筛选器字符串无效.筛选器字符串必须包含筛选器的说明,后跟竖线(|)和筛选模式.不同筛选悬想的字符串还必须以竖线分隔.例如:"文本文件(*.txt)|*.txt|所有文件(*.*)|*.*".