我希望只将一种文件类型读取到我的列表视图中,因此如果文件以 .txt 结尾,它应该只读取 .txt 文件,对于 csv 和 excel 文件也是如此。
public void doexcel()
{
OleDbConnection cnn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + textBox_Choose.Text +
";Extended Properties='Excel 12.0 XML;HDR=YES;';");
string name; name = "";
OleDbCommand oconn = new OleDbCommand("SELECT * from [" + "Sheet1$" + "]", cnn);
cnn.Open();
OleDbDataAdapter adp = new OleDbDataAdapter(oconn);
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow row in dt.Rows)
{
ListViewItem item = new ListViewItem(row[0].ToString());
for (int i = 1; i < dt.Columns.Count; i++)
{
item.SubItems.Add(row[i].ToString());
}
listView1.Items.Add(item);
}
}
public void dotxt()
{
string filepath = textBox_Choose.Text;
FileStream yaNew = File.Open(filepath, FileMode.Open, FileAccess.Read);
StreamReader yaRead = new StreamReader(yaNew);
string yaView = yaRead.ReadToEnd();
yaRead.Close();
yaNew.Close();
String[] yaArray = yaView.Split(new char[] { '\n' });
foreach (string ya in yaArray)
{
listView1.Items.Add(ya);
}
}
private void button_Choose_Click(object sender, EventArgs e)
{
//Call the OpenFileDialog Object and name it
OpenFileDialog explore = new OpenFileDialog();
//Set the directory path
explore.InitialDirectory = @"c:\MyProject";
//set the file types
explore.Filter = "All files (*.*)|*.*|All files (*.*)|*.*";
explore.FilterIndex = 2;
explore.RestoreDirectory = true;
//show result in the textbox
if (explore.ShowDialog() == DialogResult.OK)
{
textBox_Choose.Text = explore.FileName;
}