c# winform ListView导出Excel(2017)

之前网上有人分享的c# winform ListView导出Excel(2017),发现将代码应用到项目里面导出的Excel总是会出现 双引号和制表符号,自己在网上看到有人用npoi导出Excel,结合之前的代码进行改造成这个。文件扩展名使用 (.xlsx)

添加npoi的程序包,解决方案--引用(鼠标右击)--管理NuGet程序包---在搜索框输入npoi--安装第一个

 1 /// <summary>
 2         /// 具体导出的方法
 3         /// </summary>
 4         /// <param name="listView">ListView</param>
 5         /// <param name="strFileName">导出到的文件名</param>
 6 
 7         private void DoExport(ListView listView, string strFileName)
 8         {
 9 
10             int rowNum = listView.Items.Count;
11             int columnNum = listView.Items[0].SubItems.Count; 
12             int columnIndex = 0;
13 
14             if (rowNum == 0 || string.IsNullOrEmpty(strFileName))
15             {
16 
17                 return;
18 
19             }
20 
21             if (rowNum > 0)
22             {
23 
24 
25                 XSSFWorkbook workBook = new XSSFWorkbook();  //实例化XSSF
26                 XSSFSheet sheet = (XSSFSheet)workBook.CreateSheet();  //创建一个sheet
27 
28                 IRow frow0 = sheet.CreateRow(0);  // 添加一行(一般第一行是表头)
29                 foreach (ColumnHeader dc in listView.Columns)
30                 {
31                     frow0.CreateCell(columnIndex).SetCellValue(dc.Text);
32                     columnIndex++;
33                 }
34 
35                 //将ListView中的数据导入Excel中
36                 for (int i = 0; i < rowNum; i++)
37                 {
38                     IRow frow1 = sheet.CreateRow(i + 1);  //之所以从i+1开始 因为第一行已经有表头了                   
39                     for (int j = 0; j < columnNum; j++)
40                     {
41                         frow1.CreateCell(j).SetCellValue(listView.Items[i].SubItems[j].Text);                     
42 
43                     }
44 
45                 }
46             
47              
48                 try
49                 {
50                     using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
51                     {
52                         workBook.Write(fs);  //写入文件
53                         workBook.Close();  //关闭
54                     }
55                     MessageBox.Show("导出成功");
56                 }
57                 catch (Exception)
58                 {
59                     workBook.Close();
60                 }              
61 
62             }
63 
64         }

猜你喜欢

转载自www.cnblogs.com/xujunheng/p/11294004.html
今日推荐