vb.net中datagradview 另存为excel文件的问题
在vb.net中遇到一个问题,请教高手如何解决,谢谢!
vb.net中datagridview另存为excel文件后一些数字数据导出后格式不正确,主要有以下问题:
1、长的数字保存excel后变成了科学计数法,如我的单据号200807000123到excel后2.00807E+11
2、以零开头的数字到excel中零没有了,如我的物料代码012345到excel后成了12345
另存为excel的方法是从网上找的:
模块中声明:
Public Sub DcExcel(ByVal DGV As DataGridView)
'把datagridview中的数据导出到excel
Dim wapp As New Microsoft.Office.Interop.Excel.Application
Dim wsheet As Microsoft.Office.Interop.Excel.Worksheet
Dim wbook As Microsoft.Office.Interop.Excel.Workbook
On Error Resume Next
wapp.Visible = True
wbook = wapp.Workbooks.Add()
wsheet = wbook.ActiveSheet
Dim iX As Integer
Dim iY As Integer
Dim iC As Integer
For iC = 0 To DGV.Columns.Count - 1
wsheet.Cells(1, iC + 1).Value = DGV.Columns(iC).HeaderText
wsheet.Cells(1, iC + 1).Font.Bold = True
Next
wsheet.Rows(2).select()
For iX = 0 To DGV.Rows.Count - 1
For iY = 0 To DGV.Columns.Count - 1
wsheet.Cells(iX + 2, iY + 1).value = DGV(iY, iX).Value.ToString
Next
Next
End Sub
导出按钮代码:
Call DcExcel(DataGridView1)
答案:Public Class Cls导入数据
Dim xlApp As New Excel.Application()
Dim xlBook As Excel.Workbook
Dim xlSheet As Excel.Worksheet
Dim A = "A"
Public Function 导出到Excel(ByVal Dt表 As DataTable) As Boolean
Dim rowIndex, colIndex As Integer
rowIndex = 1
colIndex = 0
xlBook = xlApp.Workbooks().Add
xlSheet = xlBook.Worksheets("sheet1")
Dim Table As New DataTable()
Table = CreaTable()
'将所得到的表的列名,赋值给单元格
Dim Col As DataColumn
Dim Row As DataRow
For Each Col In Table.Columns
colIndex = colIndex + 1
xlApp.Cells(1, colIndex) = Col.ColumnName
Next
'得到的表所有行,赋值给单元格
For Each Row In Table.Rows
rowIndex = rowIndex + 1
colIndex = 0
For Each Col In Table.Columns
colIndex = colIndex + 1
xlApp.Cells(rowIndex, colIndex) = Row(Col.ColumnName)
Next
Next
With xlSheet
.Range(.Cells(1, 1), .Cells(1, colIndex)).Font.Name = "黑体"
'设标题为黑体字
.Range(.Cells(1, 1), .Cells(1, colIndex)).Font.Bold = True
'标题字体加粗
.Range(.Cells(1, 1), .Cells(rowIndex, colIndex)).Borders.LineStyle = 1
'设表格边框样式
End With
With xlSheet.PageSetup
.LeftHeader = "" & Chr(10) & "&""楷体_GB2312,常规""&10公司名称:" ' & Gsmc
.CenterHeader = "&""楷体_GB2312,常规""公司人员情况表&""宋体,常规""" & Chr(10) & "&""楷体_GB2312,常规""&10日 期:"
.RightHeader = "" & Chr(10) & "&""楷体_GB2312,常规""&10单位:"
.LeftFooter = "&""楷体_GB2312,常规""&10制表人:"
.CenterFooter = "&""楷体_GB2312,常规""&10制表日期:"
.RightFooter = "&""楷体_GB2312,常规""&10第&P页 共&N页"
End With
xlApp.SaveWorkspace()
MsgBox("保存完毕", MsgBoxStyle.Exclamation, "提示")
KillAllExcels()
'xlApp.Visible = True
End Function
Sub KillAllExcels()
Dim proc As System.Diagnostics.Process
For Each proc In System.Diagnostics.Process.GetProcessesByName("EXCEL")
proc.Kill()
Next
End Sub
end class
其他:我不会!
去论坛看看!
上一个:vb.net 中的警告
下一个:我的机器真的没有办法按装vb.net了吗?