2

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

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

它看起来像什么

我希望它看起来像什么

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();
  }
4

3 回答 3

1
Excel.Range range;

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

MSDN

于 2012-07-13T16:13:36.933 回答
0

Looks like the BestFit property is what you want, though it might be buggy:

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

于 2012-07-13T16:11:52.863 回答
0

我一直在寻找解决同一问题的方法。上面检查的答案对我没有直接作用。

它通过一个简单的添加工作:

Excel.Range range;

range = ws.get_Range("A1", "1");
range.Columns. AutoFit();
于 2015-06-29T13:18:15.270 回答