首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >NPOI、XLSX和VB.NET

NPOI、XLSX和VB.NET
EN

Stack Overflow用户
提问于 2014-05-01 18:57:44
回答 1查看 7.1K关注 0票数 1

我试图使用NPOI将XLS和XLSX文件转换为CSV文件。现在,我的代码非常适合XLS文件,但是遇到了XLSX文件的问题。

下面是使用NPOI将文件转换为CSV文件的代码(实际上这段代码将其转换为DataSet,转换为CSV在下一段代码中进行)

代码语言:javascript
运行
复制
''' <summary>
''' Import file with delimited rows, columns to datatable 
''' </summary>
''' <param name="FilePath">Path to our file</param>
''' <param name="delimiter">string for delimited imported row items</param>
''' <param name="retainHeaders">Including columns header with importing , (if true, the first row will be added as DataColumns) , (if false, DataColumns will be numbers)</param>
''' <param name="worksheetIndex">The index of the worksheet we're wanting to read from</param>
Private Function GenerateDataTableFromXls(ByVal FilePath As String, ByVal delimiter As String, ByVal retainHeaders As Boolean, ByVal worksheetIndex As Integer) As DataSet

    Dim ds As New DataSet
    Dim ext As String = Path.GetExtension(FilePath)
    Try
        'Get the excel from filepath
        Dim workbook As IWorkbook
        Dim worksheet As ISheet
        Dim sheetCount As Integer
        Dim file = New FileStream(FilePath, FileMode.Open)
        If ext.ToLower() = ".xls" Then
            workbook = New HSSFWorkbook(file)
        Else
            workbook = New XSSFWorkbook(file)
        End If


        sheetCount = workbook.NumberOfSheets

        For i As Integer = 1 To sheetCount
            Dim table As New DataTable
            worksheet = workbook.GetSheetAt(i)

            'get Excel rows
            Dim rows As Integer = worksheet.PhysicalNumberOfRows

            'get the column count
            Dim columns As Integer = worksheet.GetRow(0).PhysicalNumberOfCells

            'now for adding the column headers, if retainHeaders is True then we add the
            'actual headers in the XLS file, if not then add the column number as the header
            If retainHeaders Then
                For j As Integer = 0 To columns - 1
                    table.Columns.Add(worksheet.GetRow(0).GetCell(j).ToString())
                Next
            Else
                For k As Integer = 0 To columns - 1
                    table.Columns.Add(k.ToString())
                Next
            End If

            'now we add each row to our new DataTable
            For x As Integer = 0 To rows - 1
                Dim row As DataRow = table.NewRow()
                For y As Integer = 0 To columns - 1
                    row(y) = worksheet.GetRow(x).GetCell(y).ToString()
                Next
                table.Rows.Add(row)
            Next

            ds.Tables.Add(table)
        Next

        worksheet = Nothing
        workbook = Nothing
    Catch ex As Exception
        Me.ReturnMessage = ex.ToString()
    End Try

    Return ds
End Function

现在我们把它转换成CSV

代码语言:javascript
运行
复制
''' <summary>
''' Method for converting an XLS or XLSX file to CSV format without requiring any 3rd party
''' installs like Excel or the ACE/JET drivers
''' </summary>
''' <param name="delimiter">What's the file being delimited by</param>
''' <param name="retainHeaders">Are we exporting the headers as well</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function WriteToCSV(ByVal delimiter As String, Optional ByVal retainHeaders As Boolean = True) As Boolean
    Try
        'Dim table As DataTable = GenerateDataTableFromXls(ExcelFile.SourceFile, ",", True, ExcelFile.WorksheetNum)
        Dim ds As DataSet = GenerateDataTableFromXls(ExcelFile.SourceFile, ",", True, ExcelFile.WorksheetNum)
        Dim count As Integer = ds.Tables.Count()

        If count > 1 Then
            For i As Integer = 0 To ds.Tables.Count() - 1
                If ds.Tables(i).Rows.Count() > 0 Then
                    Using writer = New StreamWriter(String.Format(ExcelFile.TargetFile & "{0}.txt", (i + 1).ToString()))
                        For Each row As DataRow In ds.Tables(i).Rows
                            Dim first As Boolean = True
                            For Each column As DataColumn In ds.Tables(i).Columns
                                If Not first Then
                                    writer.Write(",")
                                Else
                                    first = False
                                End If
                                Dim data = row(column.ColumnName).ToString().Replace("""", """""")
                                writer.Write(String.Format("""{0}""", data))
                            Next
                            writer.WriteLine()
                        Next

                    End Using
                Else
                    Throw New Exception(Me.ReturnMessage)
                End If
            Next
        Else
            If ds.Tables(0).Rows.Count() > 0 Then
                Using writer = New StreamWriter(ExcelFile.TargetFile & ".txt")
                    For Each row As DataRow In ds.Tables(0).Rows
                        Dim first As Boolean = True
                        For Each column As DataColumn In ds.Tables(0).Columns
                            If Not first Then
                                writer.Write(",")
                            Else
                                first = False
                            End If
                            Dim data = row(column.ColumnName).ToString().Replace("""", """""")
                            writer.Write(String.Format("""{0}""", data))
                        Next
                        writer.WriteLine()
                    Next

                End Using
            Else
                Throw New Exception(Me.ReturnMessage)
            End If
        End If
        Return True
    Catch ex As Exception
        Me.ReturnMessage = ex.ToString()
        Return False
    Finally
        If File.Exists(ExcelFile.SourceFile) Then
            File.Delete(ExcelFile.SourceFile)
        End If
    End Try
End Function

我得到的错误是:

System.IndexOutOfRangeException:找不到表0。在System.Data.DataTableCollection.get_Item(Int32索引处)在E:\LodgingLogistics\Lodgx\CSVConverter\Converter.vb:line 56中的CSVConverter.Converter.WriteToCSV(字符串分隔符,布尔retainHeaders)

哪一条是这条线

代码语言:javascript
运行
复制
If ds.Tables(0).Rows.Count() > 0 Then

谁能花点时间告诉我我哪里出了问题。我使用NPOI是因为我暂时无法使用.NET 2.0。

EN

回答 1

Stack Overflow用户

发布于 2014-05-01 20:03:05

您会得到这个错误,因为它是在没有找到表的情况下输入该函数。您的COUNT变量是0,这会导致它执行the语句,其中假设您有一个表。

确保您使用的是最新版本的NPOI。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23414573

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档