stringbuilder附加带变量的文本

时间:2012-08-20 07:28:36

标签: c# asp.net-mvc

我有这条线,我如何用变量附加文字来构成标题?

  StringBuilder sb = new StringBuilder();
  week6 = model.SelectedSunday.AddDays(-7);
  week5 = week6.AddDays(-7);
  week4 = week5.AddDays(-7);
  week3 = week4.AddDays(-7);
  week2 = week3.AddDays(-7);
  week1 = week2.AddDays(-7);
  sb.AppendLine("Title, Total, " week6, week5, week4, week3, week2, week1 );

以及此代码:

 var tradesmenReportData = _reportingService.GetTradeUKKPITradesmen(model.SelectedSunday);
  var jobSortedReportData = _reportingService.GetTradeUKKPIJobSorted(model.SelectedSunday);
  foreach (var item in tradesmenReportData)
  {
    sb.AppendLine(String.Concat("\"", item.Title, "\", item.Total, "\", item.Week6, "\", ", item.Week5, "\", ", item.Week4, "\", ", item.Week3, "\", ", item.Week2, "\", ", item.Week1));

  }

在输出文件(excel)中,值有一个“附加到值?在上面的某个位置有一个额外的”。我哪里出错了?

感谢

3 个答案:

答案 0 :(得分:4)

您可以使用StringBuilder.AppendFormat

sb.AppendFormat("Title, Total, {0}, {1}, {2}, {3}, {4}, {5}"
               , week6, week5, week4, week3, week2, week1);
  

追加处理复合格式字符串返回的字符串,   包含零个或多个格式项的实例。每   format项目由a的字符串表示替换   参数数组中的相应参数。

答案 1 :(得分:1)

sb.AppendFormat("Title, Total, {0}, {1}, {2}, {3}, {4}, {5}", week6, week5, week4, week3, week2, week1 );

AppendFormat重载将使用您传递给方法的参数(week6 / week5等)替换占位符。

对于第二个片段,您可以再次使用它:

sb.AppendFormat("\"{0}\", \"{1}\", \"{2}\", \"{3}\", \"{4}\", \"{5}\", \"{6}\", \"{7}\"", item.Title, item.Total, item.Week6, item.Week5, item.Week4, item.Week3, item.Week2, item.Week1);

答案 2 :(得分:0)

您可以按照其他答案中的说明使用StringBuilder.AppendFormat;

另一个选项(例如,当有string但不是StringBuilder时),您应该使用string.Format,因为它比Concat更具可读性。例如:

sb.AppendLine(string.Format(@"\"{0}\" \"{1}\" \"{2}\" \"{3}\" \"{4}\" \"{5}\" \"{6}\" \"{7}\"", 
              item.Title, //0
              item.Total, //1
              item.Week6, //2
              item.Week5, //3
              item.Week4, //4
              item.Week3, //5
              item.Week2, //6
              item.Week1) //7
           );