可以通过以下步骤实现:
Dim excelApp As New Excel.Application
Dim excelWorkbook As Excel.Workbook = excelApp.Workbooks.Add()
Dim excelWorksheet As Excel.Worksheet = excelWorkbook.Sheets(1)
For i As Integer = 0 To dataGridView1.Rows.Count - 1
For j As Integer = 0 To dataGridView1.Columns.Count - 1
excelWorksheet.Cells(i + 1, j + 1) = dataGridView1.Rows(i).Cells(j).Value.ToString()
Next
Next
excelWorksheet.Cells.NumberFormat = "0.00" ' 设置为两位小数
excelWorksheet.Cells.Font.Bold = True ' 设置为粗体
excelWorkbook.SaveAs("路径\文件名.xlsx")
excelWorkbook.Close()
excelApp.Quit()
完整的代码示例:
Imports Excel = Microsoft.Office.Interop.Excel
Public Class Form1
Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim excelApp As New Excel.Application
Dim excelWorkbook As Excel.Workbook = excelApp.Workbooks.Add()
Dim excelWorksheet As Excel.Worksheet = excelWorkbook.Sheets(1)
For i As Integer = 0 To dataGridView1.Rows.Count - 1
For j As Integer = 0 To dataGridView1.Columns.Count - 1
excelWorksheet.Cells(i + 1, j + 1) = dataGridView1.Rows(i).Cells(j).Value.ToString()
Next
Next
excelWorksheet.Cells.NumberFormat = "0.00"
excelWorksheet.Cells.Font.Bold = True
excelWorkbook.SaveAs("路径\文件名.xlsx")
excelWorkbook.Close()
excelApp.Quit()
MessageBox.Show("导出成功!")
End Sub
End Class
这个功能可以在很多场景中使用,比如将DataGridView中的数据导出为Excel报表,方便用户进行数据分析和处理。
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅供参考,具体产品选择应根据实际需求和情况进行评估。
领取专属 10元无门槛券
手把手带您无忧上云