listview上数据存excel时,乱码怎么回事呀?
现在就是想把listview上的数据,都拿出来,存储成一个文件里
目前存为txt文件 是正常的
但是存为excel的格式时,,当打开这个文件时,里面是乱码,,中文的乱
数字,英文字符不乱
怎么回事呢? 谢谢
代码如下
namespace saveListview2files
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
this.saveFileDialog1.Filter = "文本文件|*.txt|Excel表格|*.xls";
ColumnHeader h1 = new ColumnHeader();
h1.Width = 85;
h1.Text = "编号";
ColumnHeader h2 = new ColumnHeader();
h2.Width = 100;
h2.Text = "姓名";
ColumnHeader h3 = new ColumnHeader();
h3.Width = 100;
h3.Text = "性别";
ColumnHeader h4 = new ColumnHeader();
h4.Width = 100;
h4.Text = "电话";
listView1.Columns.Add(h1);
listView1.Columns.Add(h2);
listView1.Columns.Add(h3);
listView1.Columns.Add(h4);
listView1.View = View.Details;
listView1.GridLines = true;
listView1.FullRowSelect = true;
for (int i = 0; i < 100; i++)
{
this.listView1.Items.Add(i.ToString());
this.listView1.Items[this.listView1.Items.Count - 1].SubItems.Add("姓名" + i);
if (i % 2 == 0)
this.listView1.Items[this.listView1.Items.Count - 1].SubItems.Add("男");
else
this.listView1.Items[this.listView1.Items.Count - 1].SubItems.Add("女");
this.listView1.Items[this.listView1.Items.Count - 1].SubItems.Add("139999999" + i.ToString("00"));
}
}
private void button1_Click(object sender, EventArgs e)
{
if (this.saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string file = this.saveFileDialog1.FileName;
FileInfo fi = new FileInfo(file);
StreamWriter sw = fi.CreateText();
//sw.WriteLine("ID\tName\tSex\tTel");
sw.WriteLine("编号\t姓名\t性别\t电话");
for (int i = 0; i < this.listView1.Items.Count; i++)
{
sw.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}", listView1.Items[i].Text, listView1.Items[i].SubItems[1].Text, listView1.Items[i].SubItems[2].Text, listView1.Items[i].SubItems[3].Text));
}
sw.Close();
//System.Diagnostics.Process.Start(file);
}
}
}
}
------解决方案--------------------
StreamWriter sw = new StreamWriter(file,Encoding.GetEncoding("GB2312"))
or
StreamWriter sw = new StreamWriter(file,Encoding.GetEncoding("utf-8"))
测试