【发布时间】:2018-04-07 07:00:43
【问题描述】:
我目前一直在尝试使 .csv 文件中最后一列的输出正常工作。我需要将其转换为货币。我不确定我是否对整个列使用 (i == 6) (如果这甚至是可行的)或者我是否必须这样做 (i == 13 || i == 20 || i == 27) 等每个需要转换为货币的值。
我想要完成的事情:
当点击加载库存按钮时,将读取库存记录 使用打开文件对话框控件从文本文件中读取,从文件中读取的行被标记为字段值,解析(根据需要),然后加载到列表框和类实例列表中。除了输入文件中的所有字段值之外,ListBox(和类实例列表)还应包含 QtyHand 和 Sales 列。 String.Format() 或 PadRight() 方法可用于格式化列表框内容,以使列中的所有值都对齐(假设您使用的是等宽字体)。
.csv 文件的前两行是:
Id,Item Name,StartingQty,QtyMinRestck,QtySold,QtyRStcked,UnitPrice
85-0521031,Shampoo,35,9,0,0,2.89
非常感谢任何有关解决此问题的帮助。
public partial class inventoryForm : Form
{
OpenFileDialog ipFile = new OpenFileDialog();
public inventoryForm()
{
InitializeComponent();
}
private void loadInvDataButton_Click(object sender, EventArgs e)
{
inventoryListBox.Items.Clear(); //clear listbox items
if (ipFile.ShowDialog() == DialogResult.OK) //show dialog box
{
string[] file = File.ReadAllLines(ipFile.FileName); //tokenize
foreach (string line in file) //for each line in the file ...
{
string[] inventory = line.Split(','); //tokens contain numbers from the .csv file
for (int i = 0; i < inventory.Length; i++) //loop goes through each item in the inventory
{
if (i == 6) //items in the csv file that require conversion
{
double price = double.Parse(inventory[i]); //convert the value to currency, then pad
inventory[i] = String.Format("{0:C2}", price).PadRight(20, ' ');
}
else
{
inventory[i] = inventory[i].PadRight(20, ' '); //just pad the string
}
}
string item = string.Join("", inventory);
inventoryListBox.Items.Add(item);
}
}
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow! Stack Overflow 不是一个讨论论坛,它是一个问答网站,您可以在其中提出可以回答而不是讨论的特定编程问题。您的问题缺少 1)问题和 2)代码的明确问题陈述。请阅读How do I ask a good question? 和What topics can I ask about here?,然后编辑您的问题以符合站点指南。请记住,这不是双向对话,而是问题。
-
我的第一反应是建议您在 Python 中执行此操作。你可以用不到一半的代码行数来做到这一点。 CSV 文件非常适合该语言,而且很容易学习。
-
@SDsolar - 这看起来像一个 WinForms 应用程序,那么为什么选择 Python 呢?您实际上可以使用 C# 和 linq 在一行中执行此操作...
标签: c# csv parsing for-loop openfiledialog