如何更改 EPPlus 中特定列的格式?

How do I change the format of a specific column in EPPlus?

我已经使用 EPPlus 将我的数据表从我的网站/数据库下载到 Excel sheet,第一张图片是我得到的结果。第二张图是我想要的。

问题:

显然标题仍然是字符串格式。

这样 80% 的消息就不会被隐藏,您必须将列拖出才能阅读整条消息。

编辑:完全忘记添加我的代码...

public ActionResult ExportData()
        {
            DataTable dataTable = GetData();

            using (ExcelPackage package = new ExcelPackage())
            {
                var ws = package.Workbook.Worksheets.Add("My Sheet");
                //true generates headers
                ws.Cells["1:1"].Style.Font.Bold = true;
                ws.Cells["A1"].LoadFromDataTable(dataTable, true);
                ws.Cells[ws.Dimension.Address].AutoFitColumns();

                var stream = new MemoryStream();
                package.SaveAs(stream);

                string fileName = "Log.xlsx";
                string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";

                stream.Position = 0;
                return File(stream, contentType, fileName);
            }
        }

        public DataTable GetData()
        {
            DataTable dt = new DataTable();

            if (ModelState.IsValid)
            {
                using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MySqlConnection"].ConnectionString))
                {
                    using (SqlCommand comm = conn.CreateCommand())
                    {
                        comm.Parameters.AddWithValue("@val1", Session["myID"]);
                        comm.Parameters.AddWithValue("@val2", "%" + Session["mySearchString"] + "%");
                        comm.CommandText = "SELECT * FROM dbo.Log WHERE CustomerId = @val1 AND Message LIKE @val2";
                        try
                        {
                            conn.Open();
                            dt.Load(comm.ExecuteReader());
                        }
                        catch (SqlException e)
                        {
                            throw new Exception(e.ToString());
                        }
                    }
                }
            }
            return dt;
        }

只需要设置Numberformat.Format字符串即可。像这样:

ws.Column(2).Style.Numberformat.Format = "hh:mm:ss";

如果你想定制实际的,网上有很多资源,比如 http://www.ozgrid.com/Excel/excel-custom-number-formats.htm。或者您可以直接在 excel 中打开它,将格式设置为 Custom 并尝试使用字符串。