分享

ListView导出到Excel的方法

 xihayouyi 2016-06-24

今天写了一个把ListView中的内容导出到Excel的公共方法,传入一个类型为ListView的参数,就可以了,还是满方便的!大家给点意见吧!  
public static void ExpToExcel(ListView listviewname)
  {
   if (listviewname.Items.Count == 0) return;
   Excel.Application excel = new Excel.Application();
   Excel.Workbooks workbooks = excel.Workbooks;  
   Excel.Workbook workbook = workbooks.Add(Excel.XlWBATemplate.xlWBATWorksheet);
   Excel.Sheets worksheets = workbook.Worksheets;
   Excel.Worksheet sheet = (Excel.Worksheet) worksheets.get_Item(1);
   excel.Visible = true;

   Excel.Range range;
   excel.Cells.Select();
   excel.Cells.RowHeight = 30;
   excel.Cells.Font.Size = 10;
   excel.Cells.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; 

   int rowPos = 2;
   range = excel.get_Range(sheet.Cells[rowPos,1],sheet.Cells[rowPos,1]);
   range.Select();

   for(int i=1;i<=listviewname.Columns.Count;i++)
   {
    range = excel.get_Range(sheet.Cells[rowPos,i],sheet.Cells[rowPos,i]);
    range.Borders.LineStyle = 1;
    range.Font.Name = "华文仿宋";
    range.Font.Size = 16;
    range.Font.Bold = true;
    range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
    range.ColumnWidth = 18;
    sheet.Cells[rowPos,i] = listviewname.Columns[i-1].Text.ToString();
   }
   rowPos++;

   foreach(ListViewItem item in listviewname.Items)
   {
    for(int i=1;i<=listviewname.Columns.Count;++i)
    {
     range = excel.get_Range(sheet.Cells[rowPos,i],sheet.Cells[rowPos,i]);
     range.Borders.LineStyle = 1;
     range.Font.Name = "华文仿宋";
     range.Font.Size = 12;
     range.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter;
     sheet.Cells[rowPos,i] = item.SubItems[i-1].Text;
    }
    rowPos++;
   }

  }

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 全屏 打印 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多