c#操作excel方式一:stream简单读写excel
![Rank: 8](images/default/star_level3.gif) ![Rank: 8](images/default/star_level3.gif)
- UID
- 1066743
|
![](http://images.eccn.com/silabs/silicon_chip_980x60_202203.jpg)
c#操作excel方式一:stream简单读写excel
需要命名空间
using System.IO;
界面:
![](https://img-my.csdn.net/uploads/201304/11/1365669701_6748.png)
记得添加openFileDialog
![](https://img-my.csdn.net/uploads/201304/11/1365669799_8620.png)
注意名字,改成跟代码里的对应
![](https://img-my.csdn.net/uploads/201304/11/1365669819_1251.png)
写文件按钮代码:
private void button2_Click(object sender, EventArgs e)
{
int i = 0;
StreamWriter aFile = null;
aFile = File.CreateText("aFile .csv");
//aFile.WriteLine(i.ToString() + "," + (i + 1).ToString() + "," + (i + 2));
aFile.WriteLine("\"" + i.ToString() + "," + (i + 1).ToString() + "," + (i + 2)+"\"");
//aFile.WriteLine("\""+i.ToString() + "," + (i + 1).ToString() +"\""+ "," + (i + 2));
aFile.Close();
aFile.Dispose();
MessageBox.Show("end!");
}
注意逗号分隔符的用法,逗号分隔符把内容分成几个单元格.
如果要在同一个单元格中写入逗号,则要在该单元格内容前后加上双引号加上,3种情况产生的格式如下:
![](https://img-my.csdn.net/uploads/201304/11/1365671544_3316.png)
aFile.WriteLine(i.ToString() + "," + (i + 1).ToString() + "," + (i + 2));
![](https://img-my.csdn.net/uploads/201304/11/1365671575_9815.png)
aFile.WriteLine("\"" + i.ToString() + "," + (i + 1).ToString() + "," + (i + 2)+"\"");
aFile.WriteLine("\""+i.ToString() + "," + (i + 1).ToString() +"\""+ "," + (i + 2));
![](https://img-my.csdn.net/uploads/201304/11/1365671696_4759.png)
读文件按钮按钮:
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string str = null;
FileStream fs = new FileStream(openFileDialog.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
StreamReader reader = new StreamReader(fs, System.Text.Encoding.UTF8);
while ((str = reader.ReadLine()) != null)
{
// split the string
//MessageBox.Show(str);
string[] strs = str.Split(',');
string show_str = "";
for(int i=0;i<strs.Length;i++)
{
if (i == strs.Length-1)
{
show_str += strs.ToString();
}
else
{
show_str += strs.ToString() + ",";
}
}
this.label1.Text = show_str;
}
reader.Close();
}
}
上面三种写入方式读出的字符串对应如下:
![](https://img-my.csdn.net/uploads/201304/11/1365671763_9923.png)
对应读出的字符串:
str=0,1,2
即strs[0]=0
strs[1]=1
strs[2]=2
![](https://img-my.csdn.net/uploads/201304/11/1365671832_1592.png)
![](https://img-my.csdn.net/uploads/201304/11/1365671891_3079.png)
对应的字符串:
str="0,1,2",
即strs[0]="0
strs[1]=1
strs[2]=2"
![](https://img-my.csdn.net/uploads/201304/11/1365672065_2804.png)
![](https://img-my.csdn.net/uploads/201304/11/1365672081_4238.png)
对应的字符串:
str="0,1",2,
即strs[0]="0
strs[1]=1"
strs[2]=2
![](https://img-my.csdn.net/uploads/201304/11/1365672222_5164.png) |
|
|
|
|
|