解决将过长数值数据导出excel时,出现科学技术法

        解决将过长数值数据导出excel时,出现科学技术法

       最近在测试合作版的机房收费系统,在将DataGridView表中的数据导出到Excel时,出现了下面的情况:

 

       经过查证,Excel只支持15位的数字运算,如果超过15位就会被科学计数,可以通过改变单元格格式为文本,那么在将DataGridView中的数据导出时,就应该将数值型数据转化为文本文件,其代码如下:

 

        '定义DataGridView1的行
        Dim intRows As Integer
        '定义DataGridView1的列
        Dim intCols As Integer
        '建立Excel
        Dim xlApp As New Microsoft.Office.Interop.Excel.Application()
        '显示Excel窗口
        xlApp.Visible = True
        '添加新的工作薄
        xlApp.Application.Workbooks.Add()

        '*****Excel的表头******  
        xlApp.Range("A1", "E1").Font.Bold = True                '字体加粗  
        xlApp.Range("A1", "E1").Font.ColorIndex = 32            '字体颜色蓝色  
        xlApp.Range("A1", "E1").Font.Size = 25                  '字号25  
        xlApp.Range("A1", "E1").Merge()
        xlApp.Cells(1, 1).value = "学生充值记录"                '表头内容,在第一行,第三列  

        '*****Excel表内容******  
        xlApp.Range("A2", "E2").Font.Bold = True               '字体加粗  
        xlApp.Range("A2", "E2").Font.Size = 14                 '字号  
        xlApp.Range("A1", "E1").HorizontalAlignment = 3        '指定单元格,水平居中(此处多余)  
        xlApp.Cells.HorizontalAlignment = 3                    '所有单元格,水平居中  
        'xlApp.pagesetup.CenterHorizontally = True             '设置页面水平居中  

        xlApp.Cells.EntireColumn.AutoFit()
        Dim cols As Integer                                    '定义col为datagridview1的列
        For cols = 1 To DataGridView1.Columns.Count
            xlApp.Cells(2, cols) = DataGridView1.Columns(cols - 1).HeaderText
        Next

        '向Excel中逐条导入数据
        For intRows = 0 To DataGridView1.RowCount - 1
            
            For intCols = 0 To DataGridView1.ColumnCount - 1
                If Me.DataGridView1(intCols, intRows).Value Is System.DBNull.Value Then
                    xlApp.Cells(intRows + 3, intCols + 1) = ""
                Else
                    xlApp.Cells(intRows + 3, intCols + 1) = "'" & DataGridView1(intCols, intRows).Value.ToString
                End If
            Next intCols

        Next intRows
        xlApp.Cells.EntireColumn.AutoFit()                       '自动调整列宽

        那么在生成Excel每个单元格数据的时候就加一个单引号"'", xlApp.Cells(intRows + 3, intCols + 1) = "'" & DataGridView1(intCols, intRows).Value.ToString这个问题便迎刃而解。

评论 22
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值