Winform里将Listview里的数据导出到excel里,为什么不行啊?或者有什么其他好的办法?
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
try
{
if (listView2.Items.Count == 0)
{
MessageBox.Show("列表为空!");
}
else
{
//建2003文件版本的方法。新建工作簿。
HSSFWorkbook workbook2003 = new HSSFWorkbook();
//新建1个Sheet工作表
workbook2003.CreateSheet("Sheet1");
//获取名称为Sheet1的工作表
HSSFSheet SheetOne2003 = (HSSFSheet)workbook2003.GetSheet("Sheet1");
int itemCount = listView2.Items.Count; //listview的数据行数
int columnsCount = listView2.Columns.Count; //listview的列数
//对工作表先添加行,下标从0开始 有表头,所以+1
for (int i = 0; i < itemCount + 1; i++)
{
SheetOne2003.CreateRow(i);
}
//对每一行创建listView_pictures.Columns.Count个单元格
HSSFRow SheetRow2003 = (HSSFRow)SheetOne2003.GetRow(0); //获取Sheet1工作表的首行
HSSFCell[] SheetCell2003 = new HSSFCell[columnsCount];
for (int i = 0; i < columnsCount; i++)
{
//依次为每行创建listView_pictures.Columns.Count个单元格
SheetCell2003[i] = (HSSFCell)SheetRow2003.CreateCell(i);
SheetCell2003[i].SetCellValue(listView2.Columns[i].Text);
}
for (int i = 0; i < itemCount; i++)
{
SheetRow2003 = (HSSFRow)SheetOne2003.GetRow(i + 1); //获取Sheet1工作表的第2行(1)
SheetCell2003 = new HSSFCell[columnsCount];
for (int j = 0; j < columnsCount; j++)
{
if (j <= 3)
{
SheetCell2003[j] = (HSSFCell)SheetRow2003.CreateCell(j);
SheetCell2003[j].SetCellValue(listView2.Items[i].SubItems[j].Text);
}
else if (j == columnsCount - 1)
{
SheetCell2003[j] = (HSSFCell)SheetRow2003.CreateCell(j);
if (string.Equals(listView2.Items[i].SubItems[j].Text, ""))
{
SheetCell2003[j].SetCellValue(listView2.Items[i].SubItems[j].Text);
}
else
{
SheetCell2003[j].SetCellValue(Int32.Parse(listView2.Items[i].SubItems[j].Text));
}
}
else
{
SheetCell2003[j] = (HSSFCell)SheetRow2003.CreateCell(j);
SheetCell2003[j].SetCellValue(Double.Parse(listView2.Items[i].SubItems[j].Text));
}
}
Console.WriteLine();
}
//保存excel文件
SaveFileDialog dlg = new SaveFileDialog();
dlg.Filter = "xls文件(*.xls)|*.xls";
dlg.FileName = "";
dlg.AddExtension = true;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
FileStream file2003 = new FileStream(dlg.FileName, FileMode.Create);
workbook2003.Write(file2003);
file2003.Close();
workbook2003.Close();
}
System.Diagnostics.Process.Start(dlg.FileName);//打开刚刚保存的Excel文件
}
}
catch
{
}
}
用代码块功能插入代码,请勿粘贴截图