private void buttonExport_Click(object sender, EventArgs e)
{
SaveFileDialog exe = new SaveFileDialog();
exe.Filter = "Execl files (*.xls)|*.xls";
exe.FilterIndex = 0;
exe.RestoreDirectory = true;
//exe.CreatePrompt = true;
exe.Title = "Export Excel File";
exe.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
exe.FileName = string.Format("{0}_{1}", DateTime.Now.ToString("yyyy-MM-dd HH时mm分ss秒"), "导出");
DialogResult dr = exe.ShowDialog();
if (dr != DialogResult.OK)
{
return;
}
Stream ms;
ms = exe.OpenFile();
StreamWriter sw = new StreamWriter(ms, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
for (int i = 0; i < listAccount.Columns.Count; i++)
{
if (i > 0)
{
str += "\t";
}
str += listAccount.Columns[i].Text;
}
sw.WriteLine(str);
for (int j = 0; j < listAccount.Items.Count; j++)
{
string temp = "";
for (int k = 0; k < listAccount.Columns.Count; k++)
{
if (k > 0)
{
temp += "\t";
}
string cell = listAccount.Items[j].SubItems[k].Text;
//cell = cell.Replace(" ", "").Replace("\r", "").Replace("\n", "").Replace("\r\n", "");
temp += "\"" + cell + "\"";
}
sw.WriteLine(temp);
}
sw.Close();
ms.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
finally
{
sw.Close();
ms.Close();
}
}
public void xlsdaoru(string filepath, ListView listAccount)
{
try
{
if (File.Exists(filepath) == false)
{
FileStream fs = File.Create(filepath);
fs.Close();
}
else
{
string[] arr1 = System.IO.File.ReadAllLines(@".\log.xls", Encoding.Default);
if(arr1.Length != 0)
{
listAccount.Columns.Clear();
}
for (int x = 0; x < arr1.Length; x++)
{
string[] resultString = arr1[x].Split('\t');
if (x == 0)
{
for (int i = 0; i < resultString.Length; i++)
{
ColumnHeader ch = new ColumnHeader();
ch.Name = "a" + i.ToString();
ch.Text = resultString[i];
if (listAccount.Width-20 - ((resultString.Length - 3) * 50) > 400)
{
switch (i)
{
case 0: ch.Width = (listAccount.Width-20 - ((resultString.Length - 3) * 50))/3; break;
case 1: ch.Width = (listAccount.Width -20- ((resultString.Length - 3) * 50)) / 3; ; break;
case 2: ch.Width = (listAccount.Width-20 - ((resultString.Length - 3) * 50)) / 3; ; break;
default: ch.Width = 50; break;
}
}
else
{
switch (i)
{
case 0: ch.Width = 100; break;
case 1: ch.Width = 150; break;
case 2: ch.Width = 150; break;
default: ch.Width = 50; break;
}
}
ch.TextAlign = HorizontalAlignment.Center;
listAccount.Columns.Add(ch);
}
}
else
{
ListViewItem lvi;
lvi = new ListViewItem();
lvi.Text = resultString[0];
for (int i = 1; i < resultString.Length; i++)
{
lvi.SubItems.Add(resultString[i]);
}
listAccount.Items.Add(lvi);
listAccount.EndUpdate();
}
}
}
}
catch (Exception)
{
DialogResult dr = MessageBox.Show("数据存储文件被打开,无法加载,请关闭文件后运行程序。", "错误!!!");
System.Environment.Exit(0);
}
}