gpt4 book ai didi

c# - 将 excel 中的数据表列填充为字符串

转载 作者:太空宇宙 更新时间:2023-11-03 10:45:20 26 4
gpt4 key购买 nike

我正在从格式化(小数、日期等)的 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

任何帮助都会很好。

最佳答案

一个简单的方法是循环行并使用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;

关于c# - 将 excel 中的数据表列填充为字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23670981/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com