[英]exporting to excel from asp.net getting line breaks to display
我已经看到了与此主题相关的许多问题-但我无法获得建议。 我正在将数据集导出到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打开时,单元格中的文本自动换行?
我建议您将Excel库用于此类任务。 效果不错!
与其在Style中执行WrapText,不如尝试在Alignment中执行:
sb.AppendFormat(@" <Alignment ss:WrapText=""1"" ss:Vertical=""Bottom""/>{0}", Environment.NewLine);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.