欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

winform導(dǎo)出dataviewgrid數(shù)據(jù)為excel的方法

 更新時(shí)間:2015年01月20日 10:13:36   投稿:shichen2014  
這篇文章主要介紹了winform導(dǎo)出dataviewgrid數(shù)據(jù)為excel的方法,可實(shí)現(xiàn)將dataViewGrid視圖中的數(shù)據(jù)導(dǎo)出為excel格式的功能,非常具有實(shí)用價(jià)值,需要的朋友可以參考下

本文實(shí)例講述了winform導(dǎo)出dataviewgrid數(shù)據(jù)為excel的方法。分享給大家供大家參考。具體實(shí)現(xiàn)方法如下:

復(fù)制代碼 代碼如下:
#region 導(dǎo)出dataViewGrid視圖中的數(shù)據(jù)為xls格式 
private void btnExportList_Click(object sender, EventArgs e) 

   string fname = string.Empty; 

   SaveFileDialog sfd = new SaveFileDialog(); 

   sfd.Filter = "表格文件|*.xls"; 
   sfd.DefaultExt = "xls"; 

   if (sfd.ShowDialog() == DialogResult.OK) 
   { 
       fname = sfd.FileName; 
   } 
   else 
   { 
       return; 
   } 

   //導(dǎo)出當(dāng)前dataGridView中的所有數(shù)據(jù)到xls文件 
   //1.引入庫文件,新建lib文件夾,復(fù)制相關(guān)文件 
   //2.在項(xiàng)目中添加對(duì)這幾個(gè)dll的引用 
   //3.在內(nèi)存中建立 excel表文件 
   HSSFWorkbook workbook = new HSSFWorkbook(); 
   HSSFSheet sheet = workbook.CreateSheet("第一頁"); 

   //創(chuàng)建標(biāo)題頭 
   HSSFRow title = sheet.CreateRow(0); 
   title.CreateCell(0).SetCellValue("編號(hào)"); 
   title.CreateCell(1).SetCellValue("姓名"); 
   title.CreateCell(2).SetCellValue("性別"); 
   title.CreateCell(3).SetCellValue("年齡"); 
   title.CreateCell(4).SetCellValue("地址"); 
   title.CreateCell(5).SetCellValue("電話"); 
   title.CreateCell(6).SetCellValue("生日"); 
   for (int rowindex = 0; rowindex < dgvStudens.RowCount; rowindex++) 
   { 
       //創(chuàng)建第一行 
       HSSFRow row = sheet.CreateRow(rowindex + 1); 

       for (int colindex = 0; colindex < dgvStudens.Rows[rowindex].Cells.Count; colindex++) 
       { 
    row.CreateCell(colindex).SetCellValue((dgvStudens.Rows[rowindex].Cells[colindex].Value == null) ? null : dgvStudens.Rows[rowindex].Cells[colindex].Value.ToString()); 
       } 
       ////創(chuàng)建第一行的第一列 
       //HSSFCell cell = row.CreateCell(0); 
       //cell.SetCellType(3); 
       //cell.SetCellValue(dgvStudens.Rows[rowindex].Cells[0].Value.ToString()); 
       ////第一行第2列 
       //row.CreateCell(1).SetCellValue(dgvStudens.Rows[rowindex].Cells[1].Value.ToString()); 
       ////第一行第3列 
       //row.CreateCell(2).SetCellValue(dgvStudens.Rows[rowindex].Cells[2].Value.ToString()); 
       ////第一行第4列,age,可能會(huì)為空 
       //// row.CreateCell(3).SetCellValue(dgvStudens.Rows[0].Cells[3].Value.ToString()); 
       //row.CreateCell(3).SetCellValue((dgvStudens.Rows[rowindex].Cells[3].Value == null) ? null : dgvStudens.Rows[rowindex].Cells[3].Value.ToString()); 
   } 

   using (FileStream fs = new FileStream(fname, FileMode.Create)) 
   { 

       workbook.Write(fs); 
   } 

   ; 

}  
#endregion

希望本文所述對(duì)大家的C#程序設(shè)計(jì)有所幫助。

相關(guān)文章

最新評(píng)論