只要每个“项目”都是数字或每个项目都是字母数字,这就有效。当我有数字和字母数字的“项目”时,它不会正确填写值。
这是代码:
public void updateInventory()
{
try
{
if (File.Exists(inventoryUpdateDirectory + "inventoryUpdate.csv"))
{
csvReader csv = new csvReader();
DataTable inventory = csv.read(inventoryUpdateDirectory + "inventoryUpdate.csv");
//int test = inventory.Rows.Count;
string sql = "";
foreach (DataRow inventoryItem in inventory.Rows)
{
try
{
sql = " Update Inventory set OnHand = " + inventoryItem[1] + " WHERE Sku = '" + inventoryItem[0].ToString().Trim() + "'";
//executeSQL(sql);
}
catch { }
}
File.Delete(inventoryUpdateDirectory + "inventoryUpdate.csv");
}
else
{
writeToFile("fileDoesntExist", inventoryUpdateDirectory + "error.txt");
}
}
catch { }
}
这是它读取的文件:
ALB001,0
ALB002,66
10001,0
10016,348
这将起作用:
ALB001,0
ALB002,66
这将起作用:
10001,0
10016,348
这将不起作用:
ALB001,0
ALB002,66
10001,0
10016,348
它将数组填充inventoryItem
为空{}
+ inventoryItem[0] {} object {System.DBNull}
哪个值应该是ALB001
CSV 中的第一个“列”应始终被视为字符串,因为它可以包含字母数字,第二个“列”将始终是数字。
谁能帮我解决这个问题?
我想我只需要编辑 sql 查询以将它们转换为字符串,但我不确定。
CSV 阅读器编辑:
namespace CSV
{
public class csvReader
{
public DataTable read(string strFileName)
{
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=NO;FMT=Delimited\"");
conn.Open();
string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, conn);
DataSet ds = new DataSet("CSV File");
adapter.Fill(ds);
return ds.Tables[0];
}
public DataTable read(string strFileName, bool firstRowHeaders)
{
string hdr = "NO";
if (firstRowHeaders) { hdr = "YES"; }
OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OleDb.4.0; Data Source = " + System.IO.Path.GetDirectoryName(strFileName) + "; Extended Properties = \"Text;HDR=" + hdr + ";FMT=Delimited\"");
conn.Open();
string strQuery = "SELECT * FROM [" + System.IO.Path.GetFileName(strFileName) + "]";
OleDbDataAdapter adapter = new OleDbDataAdapter(strQuery, conn);
DataSet ds = new DataSet("CSV File");
adapter.Fill(ds);
return ds.Tables[0];
}
}
}