ggyyppmm

遨游于博大精深的.net

 

ListView导出到Excel的方法

今天写了一个把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++;
   }

  }

posted on 2004-09-26 11:50  .netbc  阅读(6533)  评论(5编辑  收藏  举报

导航