如何在 C# 中生成带有 90 度字母向下旋转标题的 Excel 文件?

  • 本文关键字:旋转 标题 文件 Excel c# closedxml
  • 更新时间 :
  • 英文 :


我正在开发一个人力资源应用程序,该应用程序需要显示工作环境 excel 报告,如下图所示。

现在我正在寻找有关此主题的帮助,我正在使用ClosedXML.Excel,目前我正在使用自己创建的方法生成我的 Excel 文件,它输入对象列表并在 http 请求的响应中创建 excel 文件。这是代码:

public static bool ConvertToExcel<T>(IList<T> data, string excelName, string sheetName)
{
PropertyDescriptorCollection properties =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
foreach (PropertyDescriptor prop in properties)
table.Columns.Add(prop.Name.Replace("_"," "), Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType);
foreach (T item in data)
{
DataRow row = table.NewRow();
foreach (PropertyDescriptor prop in properties)
row[prop.Name.Replace("_", " ")] = prop.GetValue(item) ?? DBNull.Value;
table.Rows.Add(row);
}
try
{
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(table, sheetName);
System.Web.HttpContext.Current.Response.Clear();
System.Web.HttpContext.Current.Response.Buffer = true;
System.Web.HttpContext.Current.Response.Charset = "";
string FileName = excelName + ".xlsx";
System.Web.HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName);
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(System.Web.HttpContext.Current.Response.OutputStream);
System.Web.HttpContext.Current.Response.Flush();
System.Web.HttpContext.Current.Response.End();
}
}
}
catch (Exception e) 
{
throw e;
return false;
}
return true;
}

由于老板的名字很长,它以简单的百分比扩展了很多 excel 列,我想知道我是否可以实现向下旋转(90 度(标题的字母。可以使用我当前的图书馆ClosedXML.Excel来实现这一点?我想使用相同的方法来生成此工作环境报告。

事先感谢:)

您可以使用连接文本旋转样式来执行此操作:

cell.Style.Alignment.SetTextRotation(90);

谢谢@Raidri。

我更改了代码:

wb.Worksheets.Add(table, sheetName);

自:

var ws = wb.Worksheets.Add(table, sheetName);
ws.Row(1).Style.Alignment.SetTextRotation(180);
ws.Tables.FirstOrDefault().ShowAutoFilter = false;

这样,文本向下旋转 90 度,我删除了过滤器。

最新更新