日期:2014-05-18  浏览次数:20873 次

c#中导入导出excel
请教:在c#中如何打开excel文件,把数据导入DataGridView,但是要实现自由选择所打开的excel文件,而不是在DataSource中固定了;怎样将DataGridView中的数据导出为excel?

------解决方案--------------------
C# code

private void ToExcel()
        {
            

            Excel.ApplicationClass MyExcel = new Excel.ApplicationClass();
            
            MyExcel.Visible = true;
            if (MyExcel == null)
            {
                MessageBox.Show("EXCEL无法启动!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            Workbook wbook = MyExcel.Application.Workbooks.Add(Type.Missing);
            Worksheet worksheet = (Worksheet)wbook.Worksheets[1];
            //worksheet.Name = "aa";


            int rowcount = 0;       //行号
            int columncount = 0;    //列号
            //MyExcel.Application.Workbooks.Add(true);    //加入表
            columncount = this.dataGridView1.ColumnCount;   //等于DATA表里行的总数
            rowcount = this.dataGridView1.RowCount;         //等于DATA表里列的总数
            rowcount--;     //因为打开dataGridView1时是默认新增的,所以要-1条记录数
            //MessageBox.Show(rowcount.ToString());
            //Excel文件的格式是从1开始,不是0开始
            for (int m = 1; m < columncount; m++)   //去除dataGridView1的编号列,即m=1,如m=0出错
            {
                worksheet.Cells[1, m] = this.dataGridView1.Columns[m].HeaderText;//得到列标题文本
            }
            for (int i = 0; i < rowcount; i++)  //二维表填充从每一行开始
            {
                for (int j = 1; j < columncount; j++)      //填充每一行第j列单元格
                {
                    worksheet.Cells[i + 2, j] = this.dataGridView1[j, i].Value.ToString(); //i+2定位到第一行正文
                    //在填充单元格的时候如果关闭了EXCEL,程序会发生异常,下个版本有待改进。<--------------------
                }
            }
            MessageBox.Show("数据导出完毕,请保存!");

------解决方案--------------------
这个不复杂,首先读取EXCEL的路径,然后把它写入DateTable,最后再把DateTable赋给gridview,不就OK。
关键在于读取Excel的数据,给你个代码:
//opnFileName,EXCEL的路径(绝对)
string ConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + opnFileName + ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';";
OleDbConnection conn = new OleDbConnection(ConnStr);
string strExcel = "";
strExcel = "select * from [Sheet1$]";
conn.Open();
OleDbDataAdapter myCommand = new OleDbDataAdapter(strExcel, ConnStr);
//把读取的数据填入datetable (即dt)中。
myCommand.Fill(dt); 
conn.Close();
conn.Dispose();

------解决方案--------------------
1:输出到Excel
输出到Excel要调用Excel.dll文件,
Excel.dll文件的获取方法可以到网上搜索一下,
为了方便,我附件发了上来,
下面是核心代码:
Excel.Application myExcel = new Excel.Application();
myExcel.Application.Workbooks.Add(true);
myExcel.Visible = true;
string[] header ={ "1", "2", "3", "4" };
for (int i = 0; i < header.Length; i++)
{
myExcel.Cells[1, i + 1] = header[i];
}
int DGV_Row = this.dataGridView2.Rows.Count - 1;
for (int i = 0; i < DGV_Row; i++)
{
for (int j = 0; j < header.Length; j++)
{
myExcel.Cells[i + 2, j + 1] = "'" + this.dataGridView2[j, i].Value.ToString();
}
}