2

我有这一行,如何在文本中附加变量以构成标题?

  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)中,值有一个“附加到值?在上面的某处有一个额外的”。我哪里出错了?

谢谢

4

3 回答 3

5

您可以使用StringBuilder.AppendFormat

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

将通过处理包含零个或多个格式项的复合格式字符串返回的字符串附加到此实例。每个格式项都替换为参数数组中相应参数的字符串表示形式。

于 2012-08-20T07:34:03.423 回答
2
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);
于 2012-08-20T07:39:00.377 回答
0

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

您应该使用另一个选项(例如,当 havestring但不是) ,因为它比 . 更具可读性。例如:StringBuilderstring.FormatConcat

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
           );
于 2012-08-20T07:34:32.003 回答