[英]open and edit multiple .csv files in c#
My ideal is : open some .csv files (5 or 6 or more) and add 2 new columns to all opened files and finally save it. 我的理想是:打开一些.csv文件(5个或6个或更多),并向所有打开的文件添加2个新列,最后保存它。 Here is my code 这是我的代码
OpenFileDialog fopen = new OpenFileDialog();
fopen.Multiselect = true;
fopen.Filter = "(All type)|*.*";
fopen.ShowDialog();
if (fopen.FileName != null)
{
Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Open(fopen.FileName);
Excel.Worksheet sheet = wb.Sheets[1];
Excel.Range range = sheet.UsedRange;
int column = range.Columns.Count;
int row = range.Rows.Count;
textBox1.Text = fopen.FileName;
//textBox2.Text = row.ToString();
//textBox3.Text = column.ToString();
range.Cells.set_Item(1, column + 1, "Mo_stMoC");
range.Cells.set_Item(1, column + 2, "Mo_stMoCCpl");
for (int i = 2; i <= row; i++)
{
range.Cells.set_Item(i, column + 1, "0");
range.Cells.set_Item(i, column + 2, "0");
}
wb.Save();
wb.Close();
app.Workbooks.Close();
app.Quit();
}
The problem is, when I open the files and it just adding 2 columns in the first .csv file. 问题是,当我打开文件时,它仅在第一个.csv文件中添加了2列。 I'm new to C#, so what am I doing wrong here? 我是C#的新手,所以我在这里做错了什么?
you are opening multiple files , so loop through fopen.FileNames instead of just using fopen.FileName 您正在打开多个文件 ,因此遍历fopen.FileNames而不是仅使用fopen.FileName
foreach (String file in fopen.FileNames)
{
//do your thing
//edit
}
Additionally it is better to filter only csv files instead of all. 此外,最好只过滤csv文件而不是全部文件。
fopen.Filter = "CSV Files (*.csv)|*.csv";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.