C#DATAGRIDVIEW 导出EXCEL

首先需要引入程序集:Microsoft.Office.Interop.Excel  (如果没有引用过的需要右键添加引用再搜索就行了)

 

实现的方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/// <summary>
   ///
   /// </summary>
   /// <param name="fileName">文件路径</param>
   /// <param name="myDGV">控件DataGridView</param>
   private void ExportExcels(string fileName, DataGridView myDGV)
   {
       string saveFileName = "";
       SaveFileDialog saveDialog = new SaveFileDialog();
       saveDialog.DefaultExt = "xls";
       saveDialog.Filter = "Excel文件|*.xls";
       saveDialog.FileName = fileName;
       saveDialog.ShowDialog();
       saveFileName = saveDialog.FileName;
       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 < myDGV.ColumnCount; i++)
       {
           worksheet.Cells[1, i + 1] = myDGV.Columns[i].HeaderText;
       }
       //写入数值
       for (int r = 0; r < myDGV.Rows.Count; r++)
       {
           for (int i = 0; i < myDGV.ColumnCount; i++)
           {
               worksheet.Cells[r + 2, i + 1] = myDGV.Rows[r].Cells[i].Value;
           }
           System.Windows.Forms.Application.DoEvents();
       }
       worksheet.Columns.EntireColumn.AutoFit();//列宽自适应
       if (saveFileName != "")
       {
           try
           {
               workbook.Saved = true;
               workbook.SaveCopyAs(saveFileName);
           }
           catch (Exception ex)
           {
               MessageBox.Show("导出文件时出错,文件可能正被打开!\n" + ex.Message);
           }
       }
       xlApp.Quit();
       GC.Collect();//强行销毁
       MessageBox.Show("文件: " + fileName + ".xls 保存成功""信息提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
   }

 点击按钮调用

1
2
3
4
5
private void button1_Click(object sender, EventArgs e)
{
    string a = "D:" "\\KKHMD.xls";
    ExportExcels(a, dataGridView1);
}

  完成截图




以下VB代码实现从datagridview导出数据到EXCEL,并以时间作为excel的文件名

Try

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
    Dim xlApp, xlBook, xlSheet As Object
    xlApp = CreateObject("Excel.Application")
    xlBook = xlApp.Workbooks.Add
    xlSheet = xlBook.Worksheets()
    '使工作表不可见
    xlApp.Visible = False
 
    '导出DataGridView中的标题 
    Dim Cols As Integer
    For Cols = 1 To testHistoryDgv.Columns.Count
        xlApp.Cells(1, Cols) = testHistoryDgv.Columns(Cols - 1).HeaderText
    Next
 
    '逐行导出DataGridView中的数据 
    Dim i As Integer
 
    For i = 0 To testHistoryDgv.RowCount - 1
        Dim j As Integer
        For j = 0 To testHistoryDgv.ColumnCount - 1
            '判断DataGridview中的数据是否导出完毕 
            If Me.testHistoryDgv(j, i).Value Is System.DBNull.Value Then
                xlApp.Cells(i = 2, j = 1) = ""
            Else
                xlApp.Cells(i + 2, j + 1) = testHistoryDgv(j, i).Value.ToString
            End If
        Next
    Next
    '定义文件名-取系统时间作为excel文件名
    Dim fileName As String = Format(Now, "yyyyMMdd") + Format(Now, "HH:mm:ss").Replace(":", "")
    ’excelPath是文件路径,通过配置文件配置
    Dim flg As Boolean = xlBook.SaveAs(excelPath & fileName & ".xlsx")
    If flg = True Then
        MessageBox.Show("操作成功", "XXXX", MessageBoxButtons.OK, MessageBoxIcon.Asterisk)
    End If
    '关闭Excel线程
    xlApp.Quit()
    xlApp = Nothing
    xlBook = Nothing
    xlSheet = Nothing
Catch ex As Exception
    '异常捕捉
    LogUtil.err(ex.ToString)
    MessageBox.Show("系统异常", "Message", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try

阅读更多
想对作者说点什么? 我来说一句

C#dataGridview导出excel的三种方法

2012年10月17日 282KB 下载

没有更多推荐了,返回首页

不良信息举报

C#DATAGRIDVIEW 导出EXCEL

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭