2016-06-22 78 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