我的理想是:打开一些.csv文件(5或6或更多)并为所有打开的文件添加2个新列,最后保存。这是我的代码
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();
}
问题是,当我打开文件时,它只在第一个.csv文件中添加了2列。 我是C#的新手,所以我在这里做错了什么?
答案 0 :(得分:2)
你正在打开multiple files,所以循环通过fopen.FileNames而不是仅仅使用fopen.FileName
foreach (String file in fopen.FileNames)
{
//do your thing
//edit
}
此外,最好只过滤csv文件而不是全部。
fopen.Filter = "CSV Files (*.csv)|*.csv";