C# 导出DataGridView数据到Excel表

来源:互联网 发布:java用类输出学生信息 编辑:程序博客网 时间:2024/05/24 15:41
方法1:

添加引用  如图

  


 private void button7_Click(object sender, EventArgs e)
        {


            string fileName = "";
            string saveFileName = "";
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.DefaultExt = "xlsx";
            saveDialog.Filter = "Excel文件|*.xlsx";
            saveDialog.FileName = fileName;
            saveDialog.ShowDialog();
            saveFileName = saveDialog.FileName;
            progreesBar.Visible = true;
            if (saveFileName.IndexOf(":") < 0) return; //取消
            Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
            if (xlApp == null)
            {
                MessageBox.Show("无法创建Excel对象,您的电脑可能未安装Excel");
                return;
            }
            Microsoft.Office.Interop.Excel.Workbooks workbooks = xlApp.Workbooks;
            Microsoft.Office.Interop.Excel.Workbook workbook = workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet);
            Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1];//取得sheet1 
            //写入标题             
            for (int i = 0; i < dataGridView1.ColumnCount; i++)
            { worksheet.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText; }
            //写入数值
            for (int r = 0; r < dataGridView1.Rows.Count; r++)
            {
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    worksheet.Cells[r + 2, i + 1] = dataGridView1.Rows[r].Cells[i].Value;
                }
                progreesBar.Value += 100 / dataGridView1.Rows.Count;
                System.Windows.Forms.Application.DoEvents();
            }
            worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
            progreesBar.Value = 100;
            MessageBox.Show(fileName + "保存成功", "提示", MessageBoxButtons.OK);
            progreesBar.Value = 0;
            progreesBar.Visible = false;
            if (saveFileName != "")
            {
                try
                {
                    workbook.Saved = true;
                    workbook.SaveCopyAs(saveFileName);  //fileSaved = true;                 
                }
                catch (Exception ex)
                {//fileSaved = false;                      
                    MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
                }
            }
            xlApp.Quit();
            GC.Collect();
        }


方法二:

流输入

 

   if (dataGridView1.RowCount== 0)
            {
                MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }
            else
            {
                saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
                saveFileDialog.FilterIndex = 0;
                saveFileDialog.RestoreDirectory = true;
                saveFileDialog.CreatePrompt = true;
                saveFileDialog.Title = "导出文件保存路径";


                saveFileDialog.ShowDialog();
                progreesBar.Visible = true;
                Stream myStream;
                myStream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
                string str = "";


                try
                {
                    //写标题
                    for (int i = 0; i < dataGridView1.ColumnCount ; i++)
                    {
                        if (i > 0)
                        {
                            str += "\t";
                        }
                        str += dataGridView1.Columns[i].HeaderText.ToString();
                    }
                    sw.WriteLine(str);
                    //写内容
                    for (int j = 0; j < dataGridView1.RowCount; j++)
                    {
                        string tempStr = "";
                        for (int k = 0; k < dataGridView1.Columns.Count; k++)
                        {
                            if (k > 0)
                            {
                                tempStr += "\t";
                            }
                            tempStr += dataGridView1.Rows[j].Cells[k].Value;
                        }
                        sw.WriteLine(tempStr);
                        progreesBar.Value += 100 / dataGridView1.Rows.Count;
                    }
                    sw.Close();
                    myStream.Close();
                    progreesBar.Value = 100;
                    MessageBox.Show("数据已经成功导出到:" + saveFileDialog.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    progreesBar.Value = 0;
                    progreesBar.Visible = false;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "友情提示", MessageBoxButtons.OK);
                }
                finally
                {
                    sw.Close();
                    myStream.Close();
                }
            }