我正在从格式化的Excel工作表中填写数据表(小数,日期等)。
我的问题是列被格式化为excel表,但我需要将所有列填充为字符串,我该怎么做?
我的导入方法:
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
任何帮助都会很好。
答案 0 :(得分:1)
一种简单的方法是循环行并使用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;
答案 1 :(得分:1)
请尝试在excel连接字符串中使用IMEX = 1,如下所示
"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=YourExcelFilePath.xls;Extended Properties=""Excel 12.0;HDR=YES;IMEX=1"""
此属性提示读者将所有值都读为文本