listview 导出 excel代码

zheng5233 2012-05-19 04:52:21
listview 导出 excel代码listview 导出 excel代码listview 导出 excel代码listview 导出 excel代码listview 导出 excel代码
...全文
45 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
laomengzi 2012-05-19
  • 打赏
  • 举报
回复
说明,pListView 为listview控件的name
添加个saveFileDialog控件,
添加个进度条progreesBar控件,就可以了
laomengzi 2012-05-19
  • 打赏
  • 举报
回复
 if (pListView.Items.Count == 0)
{
MessageBox.Show("没有数据可供导出!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
else
{
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出文件保存路径";

saveFileDialog.ShowDialog();
progreesBar.Visible = true;
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";

try
{
//写标题
for (int i = 0; i < pListView.Columns.Count; i++)
{
if (i > 0)
{
str += "\t";
}
str += pListView.Columns[i].Text.ToString();
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < pListView.Items.Count; j++)
{
string tempStr = "";
for (int k = 0; k < pListView.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += pListView.Items[j].SubItems[k].Text.ToString();
}
sw.WriteLine(tempStr);
progreesBar.Value += 100 / pListView.Items.Count;
}
sw.Close();
myStream.Close();
progreesBar.Value = 100;
MessageBox.Show("数据已经成功导出到:" + saveFileDialog.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
progreesBar.Value = 0;
progreesBar.Visible = false;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "友情提示", MessageBoxButtons.OK);
}
finally
{
sw.Close();
myStream.Close();
}
}
}



}
wocaleia 2012-05-19
  • 打赏
  • 举报
回复

//输出到excel
先实例化对象 excel
DSGIS.EXCEL.SmartExcel excel = new DSGIS.EXCEL.SmartExcel();
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "XLS (*.XLS)|*.xls";
saveFileDialog1.Title = "Save an Excel File";
saveFileDialog1.ShowDialog();
if (saveFileDialog1.FileName != "")
{
if (excel.CreateFile(saveFileDialog1.FileName))
{
//创建新Xls成功
excel.PrintGridLines = false;
DataTable dt2 = (DataTable)this.datagridGPSCars.DataSource;
for (int j = 0; j < dt2.Columns.Count; j++)
{

excel.WriteStringValue(1, j + 1, dt2.Columns[j].ColumnName);
}
for (int i = 0; i < dt2.Rows.Count; i++)
{
for (int j = 0; j < dt2.Columns.Count; j++)
{
excel.WriteStringValue(i + 2, j + 1, this.datagridGPSCars[j, i].Value.ToString());
}
}
excel.CloseFile();
}
else
{
MessageBox.Show("创建新文件失败!");
}
}

110,566

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧