2011-12-29 7 views
0

내 응용 프로그램에서는 Excel로 datagridview를 내보내는 요구 사항이 있습니다.Excel로 C# datagridview를 내보내는 방법

다음 소스 코드를 사용 중입니다. 다음 질문에 대한 전문가의 조언을 원했습니다.

  1. 내 코드가 올바른지 아닌지? 내가 선택한 경로에 저장된 파일을 가져 오지 않기 때문입니다.

  2. 그리드에서 데이터를 내보낼 때 성능 문제가 있습니까? 그리드에서 사용할 수있는 데이터가 많을 수 있습니다.

  3. 네임 스페이스 "Microsoft.Office.Interop.Excel"을 사용하고 있는데 맞는지 확실하지 않습니까?
private void btnSaveResult_Click(object sender, EventArgs e) 
     { 
      try 
      { 
       if (this.saveFileDialog.ShowDialog() == DialogResult.OK) 
       { 
        saveFileDialog.Filter = "Execl files (*.xls)|*.xls"; 
        saveFileDialog.FilterIndex = 0; 
        saveFileDialog.RestoreDirectory = true; 
        saveFileDialog.CreatePrompt = true; 
        saveFileDialog.Title = "Export Excel File To"; 
        Microsoft.Office.Interop.Excel.ApplicationClass ExcelApp = new Microsoft.Office.Interop.Excel.ApplicationClass(); 
        ExcelApp.Application.Workbooks.Add(Type.Missing); 
        ExcelApp.Columns.ColumnWidth = 30; 
        for (int i = 0; i < grdResult.Rows.Count; i++) 
        { 
         DataGridViewRow row = grdResult.Rows[i]; 
         for (int j = 0; j < row.Cells.Count; j++) 
         { 
          ExcelApp.Cells[i + 1, j + 1] = row.Cells[j].ToString(); 
         } 
        }      
        ExcelApp.ActiveWorkbook.Saved = true; 
        ExcelApp.Quit(); 
        MessageBox.Show("The Save button was clicked or the Enter key was pressed" + "\nThe file would have been saved as " + this.saveFileDialog.FileName); 

       } 
       else MessageBox.Show("The Cancel button was clicked or Esc was pressed"); 

      } 
      catch (Exception ex) 
      { 
       MessageBox.Show("Cancelled Save Operation"); 
       this.Close(); 
      } 


     } 

답변

1

추가 갔지 통합 문서로 처리하고 Workbook.SaveCopyAs (파일 경로를) 전화를받을;

0

구현 약점 : - 사용하는 자원을 확보하지 마십시오. - 항목을 하나씩 내보냄 (매우 느립니다), 그 범위가 객체 [,] (boxed int, strings, ...)를 설정할 수있는 범위입니다. - 텍스트 형식을 처리하지 않습니다 (형식에 대한 Excel의 결정이 올바르지 않습니다), -보기 및 내보내기 논리를 혼합했습니다.

1
시도에 따라 클래스

using System; 
    using System.Data; 
    using System.Configuration; 
    using System.IO; 
    using System.Web; 
    using System.Web.Security; 
    using System.Web.UI; 
    using System.Web.UI.WebControls; 
    using System.Web.UI.WebControls.WebParts; 
    using System.Web.UI.HtmlControls; 

    /// <summary> 
    /// Summary description for GridViewExportUtil 
    /// </summary> 
    public class GridViewExportUtil 
    { 
public GridViewExportUtil() 
{ 
    // 
    // TODO: Add constructor logic here 
    // 
} 
    public static void ExportGridView(string fileName, GridView gv, Label header, Label date) 
     { 
      HttpContext.Current.Response.Clear(); 
      HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", fileName)); 
      HttpContext.Current.Response.ContentType = "application/ms-excel"; 

      using (StringWriter sw = new StringWriter()) 
      { 
       using (HtmlTextWriter htw = new HtmlTextWriter(sw)) 
       { 
        gv.AllowPaging = false; 
        // Create a table to contain the grid 
        Table table = new Table(); 

        // include the gridline settings 
        table.GridLines = gv.GridLines; 

        gv.Style["font-family"] = "Tahoma"; 
        // add the header row to the table 

        if (gv.HeaderRow != null) 
        { 
         GridViewExportUtil.PrepareControlForExport(gv.HeaderRow); 
         gv.HeaderRow.BackColor = System.Drawing.Color.Lavender; 
         gv.HeaderRow.ForeColor = System.Drawing.Color.Green; 

         table.Rows.Add(gv.HeaderRow); 
        } 
        // add each of the data rows to the table 
        foreach (GridViewRow row in gv.Rows) 
        { 
         GridViewExportUtil.PrepareControlForExport(row); 
         table.Rows.Add(row); 
        } 
        // add the footer row to the table 
        if (gv.FooterRow != null) 
        { 
         GridViewExportUtil.PrepareControlForExport(gv.FooterRow); 
         table.Rows.Add(gv.FooterRow); 
        } 
        htw.WriteLine("<br>"); 
        // htw.WriteLine("&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"); 
        if (header.Text != null) 
        { 
         header.Font.Size = 15; 
         header.Font.Bold = true; 
         header.ForeColor = System.Drawing.Color.Blue; 
         header.RenderControl(htw); 
        } 
        htw.WriteLine("</p>"); 
        // render the table into the htmlwriter 
        table.RenderControl(htw); 
        htw.WriteLine("<br>"); 
        htw.WriteLine("Report taken on :", System.Drawing.FontStyle.Bold); 
        if (date.Text != null) 
        { 
         date.ForeColor = System.Drawing.Color.Blue; 
         date.RenderControl(htw); 
        } 
        // render the htmlwriter into the response 
        HttpContext.Current.Response.Write(sw.ToString()); 
        HttpContext.Current.Response.End(); 
       } 
      } 
     } 

    /// <summary> 
    /// Replace any of the contained controls with literals 
    /// </summary> 
    /// <param name="control"></param> 
    private static void PrepareControlForExport(Control control) 
     { 
      for (int i = 0; i < control.Controls.Count; i++) 
      { 
       Control current = control.Controls[i]; 
       if (current is LinkButton) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as LinkButton).Text)); 
       } 
       else if (current is ImageButton) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as ImageButton).AlternateText)); 
       } 
       else if (current is HyperLink) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as HyperLink).Text)); 
       } 
       else if (current is DropDownList) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as DropDownList).SelectedItem.Text)); 
       } 
       else if (current is CheckBox) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as CheckBox).Checked ? "True" : "False")); 
       } 
       else if (current is Label) 
       { 
        control.Controls.Remove(current); 
        control.Controls.AddAt(i, new LiteralControl((current as Label).Text)); 
       } 

       if (current.HasControls()) 
       { 
        GridViewExportUtil.PrepareControlForExport(current); 
       } 
      } 
     } 
    } 

그리고 당신이 그들을 원하지 않는 경우 필요에 따라 변경합니다 .. 라벨을 제거

protected void Button1_Click(object sender, EventArgs e) 
     { 
    Label1.Visible = true; 
    Label2.Visible = true; 

    Label1.Text = "Login Information Data"; 
    Label2.Text = Convert.ToString(System.DateTime.Now); 

    if (GridView1.Visible == true) 
    { 
     // GridViewExportUtil.Export("StateReport.xls", GridView1); 
     GridViewExportUtil.ExportGridView("LoginInformation.xls", GridView1, Label1, Label2); 
    } 

     } 

아래로 사용합니다.

관련 문제