1、StreamWriter 类主要用于向流中写入数据
private void Browse_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
}
private void 追加文件_Click(object sender, EventArgs e)
{
StreamWriter sw = File.AppendText(textBox1.Text); //在原文件末尾加内容
//StreamWriter sw = new StreamWriter(textBox1.Text); //覆盖原文件
sw.WriteLine("追逐梦想");
sw.WriteLine("sdfsdf");
sw.Flush(); //加不加sWrete.Flush()没有关系。不用Flush相当于一次性写入所有,用了Flush,表示不等后面的,先把当前的写入
sw.Close();
}
2、StreamReader 类主要用于向流中读出数据
private void Browse_Click(object sender, EventArgs e)
{
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
textBox1.Text = openFileDialog1.FileName;
}
private void 追加文件_Click(object sender, EventArgs e)
{
StreamWriter sw = File.AppendText(textBox1.Text);
//StreamWriter sw = new StreamWriter(textBox1.Text);
sw.WriteLine("追逐梦想");
sw.WriteLine("sdfsdf");
sw.Flush();
sw.Close();
}
private void 读取文件_Click(object sender, EventArgs e)
{
StreamReader sr = new StreamReader(textBox1.Text);
while (sr.Peek() != -1)
{
string str = sr.ReadLine();
textBox2.AppendText(str + "\r\n");
}
sr.Close();
}
3、office自带库处理Excel,using Excel = Microsoft.Office.Interop.Excel;
private void 读取表格_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + textBox1.Text + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
DataTable dtSheetName = connection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "Table" });
string[] strTableName = new string[dtSheetName.Rows.Count];
for(int k = 0;k < dtSheetName.Rows.Count;k++)
{
strTableName[k] = dtSheetName.Rows[k]["TABLE_NAME"].ToString();
comboBox1.Items.Add(strTableName[k]);
}
connection.Close();
comboBox1.Visible = true;
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
comboBox1.Visible = false;
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + textBox1.Text + ";" + ";Extended Properties=\"Excel 12.0;HDR=YES;IMEX=1\"";
OleDbConnection connection = new OleDbConnection(connectionString);
connection.Open();
OleDbDataAdapter myCommand = null;
DataTable dt = new DataTable();
string strExcel = "select*from[" + comboBox1.SelectedItem.ToString() + "]";
myCommand = new OleDbDataAdapter(strExcel, connectionString);
dt = new DataTable();
myCommand.Fill(dt);
dataGridView1.DataSource = dt;
connection.Close();
}