我想从一个文件夹中一个一个地读取 xlsx 文件。我目前正在使用一个按钮来浏览单个文件,但我想使用此按钮来浏览我拥有这些文件的文件夹。所以,当我选择这个文件夹时,程序应该自动运行文件夹中的所有文件,一个接一个。
这是我的代码:
class RatWalk
{
public List steps = new List();
// reads data from excel file
public void LoadFromFile(String fileName)
{
steps.Clear();
XlsFile file = new XlsFile(fileName);
try
{
//everything I want to do
}
catch
{
}
}
private void InitializeComponent()
{
EventHandler handler = new EventHandler(OnClick);
button.Text = "Browse for the XLS file";
// button properties
this.Controls.Add(button);
}
// Browses for the file and loads the selected Excel file
private void OnClick(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
if (fileDialog.ShowDialog() != DialogResult.OK)
return;
ratWalk.LoadFromFile(fileDialog.FileName);
// Whatever I want to do
}
}
我想改变它,当我点击按钮并选择文件夹时,它会一个一个地运行文件夹中的所有文件。
请您参考如下方法:
这将适用于所选文件夹中的每个 xlsx 文件:
string selectedFolder = string.Empty;
FolderBrowserDialog selectFolderDialog = new FolderBrowserDialog();
if (selectFolderDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
selectedFolder = selectFolderDialog.SelectedPath;
DirectoryInfo dir = new DirectoryInfo(selectedFolder);
foreach (var file in dir.GetFiles("*.xlsx"))
{
ratWalk.LoadFromFile(file.FullName);
//
}
}
