我正在使用C#创建一个自动执行某些手动过程的小应用程序。我有一个CSV文件,我必须搜索第二列(名称为#34;状态"),如果状态为"清除"然后我不需要这一行,否则我需要将此行复制到另一个文件并保存聚合文件。另外,我还想知道如何在c#中删除(自动)csv文件的某些列。这是我到目前为止所做的:(第一个按钮是"显示原始"而第二个按钮是"更改和保存"
namespace AppExcel
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private static List<string[]> ReadAndParseData(string path, char separator )
{
var parsedData = new List<string[]>();
using (var sr = new StreamReader(path))
{
string line;
while ((line = sr.ReadLine()) != null)
{
string[] row = line.Split(separator);
string[] column = line.Split('\n');
parsedData.Add(row);
}
}
return parsedData;
}
private void DrawGridView(List<string[]> parsedData)
{
dataGridView1.ColumnCount = 47;
for (int i = 0; i < 47; i++)
{
var sb = new StringBuilder(parsedData[0][i]);
sb.Replace('_', ' ');
sb.Replace("\"", "");
dataGridView1.Columns[i].Name = sb.ToString();
}
foreach (string[] row in parsedData)
{
dataGridView1.Rows.Add(row);
}
dataGridView1.Rows.Remove(dataGridView1.Rows[0]);
}
private void button1_Click(object sender, EventArgs e)
{
List<string[]> parsedData = ReadAndParseData(@"C:/Export Data.csv", ',');
DrawGridView(parsedData);
}
private void button2_Click(object sender, EventArgs e)
{
List<string[]> parsedData = ReadAndParseData(@"C:/Export Data.csv", ',');
foreach (string[] row in parsedData)
{
if (row != parsedData[0])
{
// What to insert here??
}
}
}
private void button3_Click(object sender, EventArgs e)
{
}
}
}
答案 0 :(得分:1)
你可以简单地做(如果你的文件不是很大:在这种情况下,你必须使用流读取器)
var retainedLines = File.ReadAllLines(@"C:/Export Data.csv")
.Skip(1) // if you have an header in your file and don't want it
.Where(x => x.Split(',')[1] != "clear");//don't take the lines with "clear" in second column
如果你想保留第一行(标题),你可以这样做
var retainedLines = File.ReadAllLines(@"C:/Export Data.csv")
.Where((x, i) => i == 0 || x.Split(',')[1] != "clear");//i is the index, so the first line will have i == 0
然后保存到另一个文件
File.WriteAllLines(<targetPath>, retainedLines);
如果你想删除同一个文件中的行,你的targetPath必须只是现有的......
答案 1 :(得分:1)
读取文件的一行,读取行,分成列,检查“清除”,然后写入输出。
File.WriteAllLines(outPath,
File
.ReadAllLines(inPath)
.Where(line => !line.Split(seperator)[colNum].Equals("clear")));