在excel中展开列的代码

问题描述:

当我将数据导出到excel时,它加载列但不展开列。它显示数据而不必双击该行来展开列。我可以编写一些代码自动调整列,以便单元格可以显示整个数据吗?我使用的是asp.net和c#。在excel中展开列的代码

第一张照片是它目前的样子&第二张照片显示了我想要的样子。

What it looks like

What I want it to look like

protected void Button1_Click(object sender, EventArgs e) 
{ 
    Response.Clear(); 
    Response.Buffer = true; 

    DataSet dataSet = new DataSet(); 

    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ISALog1ConnectionString"].ToString()); 
    SqlCommand cmd = new SqlCommand("exec ProxyReport", conn); 
    cmd.CommandTimeout = 200; 
    SqlDataAdapter ad = new SqlDataAdapter(cmd); 
    ad.Fill(dataSet); 

    GridView1.DataSource = dataSet.Tables[0]; 
    GridView1.DataBind(); 
    GridView2.DataSource = dataSet.Tables[1]; 
    GridView2.DataBind(); 
    GridView3.DataSource = dataSet.Tables[2]; 
    GridView3.DataBind(); 

    dataSet.Tables[0].TableName = "1"; 
    dataSet.Tables[1].TableName = "2"; 
    dataSet.Tables[2].TableName = "3"; 

    int count = 3; 

    ExcelPackage pack = new ExcelPackage(); 


    for (int i = 1; i <= count; i++) 
    { 
     DataTable table = dataSet.Tables[i.ToString()]; 
     ExcelWorksheet ws = pack.Workbook.Worksheets.Add("Top" + i); 
     ws.Cells["A1"].LoadFromDataTable(table, true); 
    } 

      Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; 
      Response.AddHeader("content-disposition", "attachment; filename=ExcelExport.xlsx"); 
      Response.BinaryWrite(pack.GetAsByteArray()); 
      Response.Flush(); 
      Response.End(); 
    } 

Excel.Range range; 

range = ws.get_Range("A1", "1"); 
range.AutoFit(); 

MSDN

+0

将这项工作,即使我使用epplus? – Cloud 2012-07-13 16:18:25

+0

@云恐怕我不知道是什么epplus – HatSoft 2012-07-13 16:19:30

+0

@云叶坐会在epplus中工作看这个链接http://epplus.codeplex.com/discussions/218294就在页面底部 – HatSoft 2012-07-13 16:24:59

貌似最佳拟合属性是你想要什么,尽管它可能是马车:

http://excelpackage.codeplex.com/discussions/248406/

我在寻找解决同一问题的方法。 上面的检查答案不直接为我工作。

它的工作与简单的加法:

Excel.Range range; 

range = ws.get_Range("A1", "1"); 
range.Columns. AutoFit(); 
+0

这应该是对有关答案的评论,因为它大部分来自它。 – Fjodr 2015-06-29 13:21:53

+0

你已经定义了@Fjodr。 但我没有足够的声望评论外国的答案。抱歉。 – 2015-06-30 14:14:39