2016-06-22 39 views
0

您好我将gridview数据导入到excel中,但不幸的是,导出文件中的数据不同,应该是一个数据表。通过mysql导出Gridview数据

enter image description here

下面是我在导出按钮脚本,你能告诉我什么是错在我的脚本。我在ASP.net由于是新

try 
{ 
    Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); 
    excel.Visible = true; 
    Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value); 
    Microsoft.Office.Interop.Excel.Worksheet sheet1 = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[1]; 
    int StartCol = 1; 
    int StartRow = 1; 
    int j = 0, i = 0; 

    //Write Headers 
    for (j = 0; j < GridView1.Columns.Count; j++) 
    { 
     Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow, StartCol + j]; 
     myRange.Value = GridView1.Columns[j].HeaderText; 
    } 

    StartRow++; 

    //Write datagridview content 
    for (i = 0; i < GridView1.Rows.Count; i++) 
    { 
     for (j = 0; j < GridView1.Columns.Count; j++) 
     { 
      try 
      { 
       Microsoft.Office.Interop.Excel.Range myRange = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[StartRow + i, StartCol + j]; 
       myRange.Value2 = GridView1.Rows[i].Cells[j].Text + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";"; 

      } 
      catch 
      { 
       GridView1.DataBind(); 
      } 
     } 
    } 
} 
catch (Exception ex) 
{ 
    MessageBox.Show(ex.ToString()); 

    // ScriptManager.RegisterClientScriptBlock(this, this.GetType(), 
    // "alertMessage", 
    // "alert(ex.ToString());", true); 

} 
+1

你为什么要在catch语句'GridView1.DataBind()绑定gridview的;'?这是唯一的地方,或者你在开始这个代码块之前完成了它,也就是在开始Excel导出之前呢?数据是否正确显示在Gridview中?您是否尝试在将其导出到Excel之前调试并检查gridview中是否有数据? – Spidey

+0

我怀疑你的'GridView'没有绑定任何单元格。尝试调试并检查数据是否正确绑定到'GridView'中。 –

回答

0

嗨,这是我经历了漫长的旅程后,我使用Aspose方法在Excel中导出Gridview,它很简单,但功能强大!希望这将有助于背后Export_button

代码:

//Instantiate a new workbook 
      Aspose.Cells.Workbook workbook = new Aspose.Cells.Workbook(); 
      //Get the first worksheet in the workbook 
      Aspose.Cells.Worksheet worksheet = workbook.Worksheets[0]; 
      //Import data from GridView control to fill the worksheet 
      worksheet.Cells.ImportGridView(GridView1, 0, 0, new Aspose.Cells.ImportTableOptions() { IsFieldNameShown = true }); 
      worksheet.AutoFitColumns(); 
      //Send result to client in XLS format 
      workbook.Save(this.Response, "export.xls", ContentDisposition.Attachment, new Aspose.Cells.XlsSaveOptions()); 
0

可以datagridview的数据使用下面的方法导出到Excel:&其粘贴

public void ExportToExcel(DataGridView dgv) 
    { 
     try 
     { 
      dgv.SelectAll(); 
      dgv.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; 
      DataObject doj = dgv.GetClipboardContent(); 
      Clipboard.SetDataObject(doj); 

      dgv.ClearSelection(); 

      Microsoft.Office.Interop.Excel.Application exap = new Microsoft.Office.Interop.Excel.Application(); 
      exap.Visible = true; 

      Workbook exwb = (Workbook)exap.Workbooks.Add(); 
      Worksheet exws = (Worksheet)exwb.Sheets["Sheet1"]; 

      exws.Paste(); 

      Clipboard.Clear(); 

      Range cell1 = exws.Cells[1, 2]; 
      Range cell2 = exws.Cells[dgv.Rows.Count + 1, dgv.ColumnCount + 1]; 
      Range cell3 = exws.Cells[1, dgv.ColumnCount + 1]; 

      Range range = exws.get_Range(cell1, cell2); 
      Range colorrange = exws.get_Range(cell1, cell3); 

      range.Borders.Weight = XlBorderWeight.xlThin; 
      colorrange.Interior.Color = System.Drawing.Color.SteelBlue; 
      colorrange.Font.Color = System.Drawing.Color.White; 

      SaveFileDialog sfd = new SaveFileDialog(); 
      sfd.Filter = "Excel File 2010 (*.xlsx)|*.xlsx|Excel File 2003 (*.xls)|*.xls"; 

      if (sfd.ShowDialog() == DialogResult.OK) 
      { 
       exwb.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
      } 

     } 

     catch(System.Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 

    } 

这种方法复制所有数据在DataGridView在Excel。您当然需要添加对Microsoft.Office.Interop.Excel的引用。

或者,如果你想导出数据表到Excel,你可以试试下面的方法:

public void ExporttoExcel(System.Data.DataTable dtbl) 
    { 
     StringBuilder Output = new StringBuilder(); 

     //The first "line" will be the Headers. 
     for (int i = 0; i < dtbl.Columns.Count; i++) 
     { 
      Output.Append(dtbl.Columns[i].ColumnName + "\t"); 
     } 

     Output.Append("\n"); 

     //Generate Cell Value Data 
     foreach (DataRow Row in dtbl.Rows) 
     { 
      if (Row.RowState != DataRowState.Deleted) 
      { 
       for (int i = 0; i < Row.ItemArray.Length; i++) 
       { 
        //Handling the last cell of the line. 
        if (i == (Row.ItemArray.Length - 1)) 
        { 

         Output.Append(Row.ItemArray[i].ToString() + "\n"); 
        } 
        else 
        { 

         Output.Append(Row.ItemArray[i].ToString() + "\t"); 
        } 
       } 
      } 
     } 

     Clipboard.SetText(Output.ToString()); 

     Microsoft.Office.Interop.Excel.Application exap = new Microsoft.Office.Interop.Excel.Application(); 
     exap.Visible = true; 

     Workbook exwb = (Workbook)exap.Workbooks.Add(); 
     Worksheet exws = (Worksheet)exwb.Sheets["Sheet1"]; 


     exws.Paste(); 

     Clipboard.Clear(); 

     Range cell1 = exws.Cells[1, 1]; 
     Range cell2 = exws.Cells[dtbl.Rows.Count, dtbl.Columns.Count]; 
     Range cell3 = exws.Cells[1, dtbl.Columns.Count]; 

     Range range = exws.get_Range(cell1, cell2); 
     Range colorrange = exws.get_Range(cell1, cell3); 

     range.Borders.Weight = XlBorderWeight.xlThin; 
     colorrange.Interior.Color = System.Drawing.Color.SteelBlue; 
     colorrange.Font.Color = System.Drawing.Color.White; 

     SaveFileDialog sfd = new SaveFileDialog(); 

     sfd.Filter = "Excel File 2010 (*.xlsx)|*.xlsx|Excel File 2003 (*.xls)|*.xls"; 

     if (sfd.ShowDialog() == DialogResult.OK) 
     { 
      exwb.SaveAs(sfd.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); 
     } 


    } 

请检查是否这些方法帮助。

+0

嗨感谢您的回复,是否可以,如果我把这个代码进入私人无效?或者我应该编辑私人并公开? – Seryu

+0

是的,你可以使该方法是私人的,但你在你想要导出的同一类中使用该方法。它会工作 – Praneeth

+0

你的意思是把代码放在我的“导出按钮”上?对不起,我是新的ASP .. – Seryu

0

使用Text.Replace("&nbsp;", "")

myRange.Value2 = GridView1.Rows[i].Cells[j].Text.Replace("&nbsp;", "") + ";" == null ? "" : GridView1.Rows[i].Cells[j].Text + ";"; 

在标记

<asp:BoundField DataField="EmployeeName" HeaderText="Name" NullDisplayText=" "/> 
+0

嗨仍然是相同的结果.. – Seryu

+0

@Seryu使用NullDisplayText =“”在标记 –

+0

对不起,我是新的ASP,但我认为我的gridview是Templatefield因为我生成这里有各种表格..如果是这样,我应该把它放在标记中? – Seryu

0

我怀疑你的GridView绑定失败。以下是您可以尝试的方法。

private void ExportToExcel() 
{ 
    //First fetch all records from grid to dataset 
    DataSet dset = new DataSet(); 
    dset.Tables.Add(); 
    //First Add Columns from gridview to excel 
    for (int i = 0; i < gridView.Columns.Count; i++) //GridView is id of gridview 
    { 
     dset.Tables[0].Columns.Add(gridView.Columns[i].HeaderText); 
    } 
    //add rows to the table 
    System.Data.DataRow dr1; 
    for (int i = 0; i < gridView.Rows.Count; i++) 
    { 
     dr1 = dset.Tables[0].NewRow(); //For Example There are only 3 columns into gridview 
     System.Web.UI.WebControls.Label lblCCName = 
      (System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblCCName"); 
     System.Web.UI.WebControls.Label lblItemName = 
      (System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblItemName"); 
     System.Web.UI.WebControls.Label lblItemCode = 
      (System.Web.UI.WebControls.Label)gridView.Rows[i].Cells[0].FindControl("lblItemCode"); 
     dr1[0] = lblCCName.Text.ToString(); 
     dr1[1] = lblItemName.Text.ToString(); 
     dr1[2] = lblItemCode.Text.ToString(); 
     dset.Tables[0].Rows.Add(dr1); 
    } 
    //below code is export dset to excel 
    ApplicationClass excel = new ApplicationClass(); 
    Workbook wBook; 
    Worksheet wSheet; 
    wBook = excel.Workbooks.Add(System.Reflection.Missing.Value); 
    wSheet = (Worksheet)wBook.ActiveSheet; 
    System.Data.DataTable dt = dset.Tables[0]; 
    System.Data.DataColumn dc = new DataColumn(); 
    int colIndex = 0; 
    int rowIndex = 4; 
    foreach (DataColumn dcol in dt.Columns) 
    { 
     colIndex = colIndex + 1; 
     excel.Cells[5, colIndex] = dcol.ColumnName; 
    } 
    foreach (DataRow drow in dt.Rows) 
    { 
     rowIndex = rowIndex + 1; 
     colIndex = 0; 
     foreach (DataColumn dcol in dt.Columns) 
     { 
      colIndex = colIndex + 1; 
      excel.Cells[rowIndex + 1, colIndex] = drow[dcol.ColumnName]; 
     } 
    } 
    wSheet.Columns.AutoFit(); 
    // Server File Path Where you want to save excel file. 
    String strFileName = Server.MapPath("~\\Images\\StockStatement.xls"); 
    Boolean blnFileOpen = false; 
    try 
    { 
     System.IO.FileStream fileTemp = File.OpenWrite(strFileName); 
     fileTemp.Close(); 
    } 
    catch 
    { 
     blnFileOpen = false; 
    } 
    if (System.IO.File.Exists(strFileName)) 
    //It checks if file exists then it delete that file. 
    { 
     System.IO.File.Delete(strFileName); 
    } 
} 

Button_Click()事件中,调用此函数。

+0

您好在编译时出现错误: ApplicationClass excel = new ApplicationClass(); -Interop Type'Microsoft.Office.Interop.Excel.ApplicationClase'不能被嵌入。 – Seryu

+0

您是否添加了所有必需的名称空间?另请参考它需要Microsoft.Office.Interop 12.0。 –

+0

对不起我应该添加哪些名称空间?是的,我已经添加Microsoft.Office.Interop 12.0我的参考.. – Seryu