我已经看到了很多关于这个问题的问题 - 但我无法得到建议。我正在将数据集导出到excel,并使用以下内容设置基本格式。我通过构建此字符串来设置基本格式:
StringBuilder sb = new StringBuilder();
sb.AppendFormat(@"<?xml version=""1.0""?>{0}", Environment.NewLine);
sb.AppendFormat(@"<?mso-application progid=""Excel.Sheet""?>{0}", Environment.NewLine);
sb.AppendFormat(@"<Workbook xmlns=""urn:schemas-microsoft-com:office:spreadsheet""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:o=""urn:schemas-microsoft-com:office:office""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:x=""urn:schemas-microsoft-com:office:excel""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:ss=""urn:schemas-microsoft-com:office:spreadsheet""{0}", Environment.NewLine);
sb.AppendFormat(@" xmlns:html=""http://www.w3.org/TR/REC-html40"">{0}", Environment.NewLine);
sb.AppendFormat(@" <Styles>{0}", Environment.NewLine);
sb.AppendFormat(@" <Style ss:ID=""Default"" ss:Name=""Normal"">{0}", Environment.NewLine);
sb.AppendFormat(@" <Alignment ss:Vertical=""Bottom""/>{0}", Environment.NewLine);
sb.AppendFormat(@" <Borders/>{0}", Environment.NewLine);
sb.AppendFormat(@" <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""/>{0}", Environment.NewLine);
sb.AppendFormat(@" <Interior/>{0}", Environment.NewLine);
sb.AppendFormat(@" <NumberFormat/>{0}", Environment.NewLine);
sb.AppendFormat(@" <Protection/>{0}", Environment.NewLine);
sb.AppendFormat(@" </Style>{0}", Environment.NewLine);
sb.AppendFormat(@" <Style ss:ID=""s62"">{0}", Environment.NewLine);
sb.AppendFormat(@" <Font ss:FontName=""Calibri"" x:Family=""Swiss"" ss:Size=""11"" ss:Color=""#000000""{0}", Environment.NewLine);
sb.AppendFormat(@" ss:Bold=""1""/>{0}", Environment.NewLine);
sb.AppendFormat(@" </Style>{0}", Environment.NewLine);
sb.AppendFormat(@" <Style ss:ID=""s63"">{0}", Environment.NewLine);
sb.AppendFormat(@" <NumberFormat ss:Format=""Short Date""/>{0}", Environment.NewLine);
sb.AppendFormat(@" </Style>{0}", Environment.NewLine);
sb.AppendFormat(@" </Styles>{0}", Environment.NewLine);
sb.Append(@"{0}\r\n</Workbook>");
return sb.ToString();
在一个单独的功能中,我正在替换
<br > with
这是有效的,直到某一点。如果我有:
Bill<br />Fred<br />Jim
作为单元格的数据,它出现在excel电子表格中:
BillFredJim
如果我单击Excel中的“自动换行”图标 - 文本将在单元格中显示。即如
Bill
Fred
Jim
我已经读过我需要添加:
ss:WrapText=""1""
如何在我的StringBuilder中包含它,以便Excel自动执行?
我尝试将其添加到该行:
sb.AppendFormat(@" <Style ss:ID=""Default"" ss:Name=""Normal"">{0}", Environment.NewLine);
所以它读到:
sb.AppendFormat(@" <Style ss:ID=""Default"" ss:WrapText=""1"" ss:Name=""Normal"">{0}", Environment.NewLine);
但是,当我尝试打开生成的Excel电子表格时,它说它已损坏。如何才能使它在excel打开时,单元格中的文本换行?
答案 0 :(得分:0)
我建议您使用Excel库执行此类任务。有一个相当不错的结果!
答案 1 :(得分:0)
而不是在Style中执行WrapText尝试在Alignment中执行:
sb.AppendFormat(@" <Alignment ss:WrapText=""1"" ss:Vertical=""Bottom""/>{0}", Environment.NewLine);