Question

I am filling a data table from an excel sheet which is formatted (decimals, dates, etc...).

My problem is that the columns are being formatted as the excel sheet, but I need to fill all the columns as string, how can I do that?

My import method:

Private Function upload(filename As String) As DataTable
        Dim FilePath__1 As String = "Uploads/"
        Try
            Dim allowdFile As String() = {".xls", ".xlsx"}
            Dim FileExt As String = ".xls"

            Dim isValidFile As Boolean = allowdFile.Contains(FileExt)
            If Not isValidFile Then
                Return Nothing
            Else
                Dim filePath__2 As String = Server.MapPath(FilePath__1) & filename

                Dim con As OleDbConnection = Nothing
                If FileExt = ".xls" Then
                    con = New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & filePath__2) + ";Extended Properties=Excel 8.0;")
                ElseIf FileExt = ".xlsx" Then
                    con = New OleDbConnection((Convert.ToString("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=") & filePath__2) + ";Extended Properties=Excel 12.0;")
                End If
                con.Open()

                Dim dt As DataTable = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing)

                Dim getExcelSheetName As String = dt.Rows(0)("Table_Name").ToString()

                Dim ExcelCommand As New OleDbCommand((Convert.ToString("SELECT * FROM [") & getExcelSheetName) + "]", con)
                Dim ExcelAdapter As New OleDbDataAdapter(ExcelCommand)
                Dim ExcelDataSet As New DataSet()
                ExcelAdapter.Fill(ExcelDataSet)
                con.Close()
                If ExcelDataSet.Tables.Count > 0 Then
                    Return ExcelDataSet.Tables(0)
                Else
                    Return Nothing
                End If
            End If
        Catch ex As Exception
            Return Nothing
        End Try
    End Function

Any help would be nice.

Was it helpful?

Solution

A simple way is to loop the rows and use ToString:

DataTable tblOld = ExcelDataSet.Tables[0];
DataTable tblNew = new DataTable();
foreach (DataColumn col in tblOld.Columns)
    tblNew.Columns.Add(col.ColumnName);
foreach (DataRow rowOld in tblOld.Rows)
{
    DataRow rowNew = tblNew.Rows.Add();
    foreach (DataColumn col in tblOld.Columns)
    {
        rowNew.SetField(col.ColumnName, rowOld.IsNull(col) ? "" : rowOld[col].ToString());
    }
} 
return tblNew;

OTHER TIPS

Please try using IMEX=1 in the your excel connection string as below

"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=YourExcelFilePath.xls;Extended Properties=""Excel 12.0;HDR=YES;IMEX=1"""

This attribute hints the reader to read all values as text

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top