免責聲明鑄造String作爲整數:這是我的第一個.NET C#項目在.NET DataTable中
我試圖導入CSV到MSSQL,但需要通過CSV值第一個迭代的消毒目的。 CSV中的一些列將是整數(稍後將用於計算),其中一些是常規的varchar。
上面的腳本似乎強制DataTable中的所有值(即行列值)作爲一個字符串,當SQL無法將字符串作爲整數寫入時,它將在稍後引發我的應用程序中的Exception。
這是我用於getCSVImport的方法,它創建一個數據表並填充它。
我在想什麼是添加另一個條件,它檢查值是一個整數,然後將其轉換爲整數(這種情況對我來說是新的,因爲PHP不會如此強大地處理類型),但我害怕這不會工作,因爲我不知道我是否可以將dataTable中的值與各種類型混合使用。
所以我的問題是,有沒有辦法讓我在不同類型的數據表中有不同的值?我下面的代碼將整行作爲一個字符串寫入,我需要將值分配爲字符串或整數。
/*
* getCsvData()
* This method will create a datatable from the CSV file. We'll take the CSV file as is.
* and collect the data as needed:
*
* - Remove those original 4 lines (worthless info)
* - Line 5 starts with the headers, remove any of the brackets around the values
* - Iterate through the rest of the fields and sanitize them before we add it to the datatable
*
*/
private DataTable getCsvData(string csv_file_path)
{
// Create a new csvData tabletable object:
DataTable csvData = new DataTable();
try
{
using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))
{
csvReader.SetDelimiters(new string[] { "," });
csvReader.HasFieldsEnclosedInQuotes = true;
int row = 1;
while (!csvReader.EndOfData)
{
// Read the string and collect the row data
string[] rowData = csvReader.ReadFields();
if (row <= 4)
{
// We want to start on row 5 as first rows are nonsense :)
// Incriment the row so that we can do our magic above
row++;
continue;
} if(row == 5)
{
// Row 5 is the headers, we need to sanitize and continue:
foreach (string column in rowData)
{
// Remove the [ ] from the values:
var col = column.Substring(1, column.Length - 2);
DataColumn datecolumn = new DataColumn(col);
datecolumn.AllowDBNull = true;
csvData.Columns.Add(datecolumn);
}
// Incriment the row so that we can do our magic above
row++;
} else
{
// These are all of the actual rows, sanitize and add the rows:
//Making empty value as null
for (int i = 0; i < rowData.Length; i++)
{
// First remove the brackets:
if (rowData[i].Substring(0,1) == "[")
{
rowData[i] = rowData[i].Substring(1, rowData[i].Length - 2);
}
// Set blank to null:
if (rowData[i] == "" || rowData[i] == "-")
{
rowData[i] = null;
}
// Lastly, we need to do some calculations:
}
// Add the sanitized row to the DataTable:
csvData.Rows.Add(rowData);
}
}
}
}
catch (Exception ex)
{
throw new Exception("Could not parse the CSV file: "+ ex.Message);
}
return csvData;
}
你的問題到底是什麼? – Kinetic
你不能將一個字符串「轉換」爲一個整數,但是你可以解析它。看看'int.Parse'或'int.TryParse'。 – Kroltan
您能否提前知道csv文件中的哪些列是數字,哪些是文本?或者可以在運行之間進行更改? –