我正在使用此代码从datagridview导出到* .txt文件

TextWriter sw = new StreamWriter(@"C:\fiscal.txt");
int rowcount = dataGridView1.Rows.Count;
for (int i = 0; i < rowcount - 1; i++)
{
sw.Write("{0,-20}", dataGridView1.Rows[i].Cells[0].Value.ToString());
}
sw.Close();


但是,如果我的datagridview的单元格大于20 letters,我想删除其中的其余部分。并只导出我的前20个字母。

最佳答案

希望Substring()将通过以下方式为您提供帮助:将代码段包含在for

string tempString = dataGridView1.Rows[i].Cells[0].Value.ToString();
if(tempString.Length>20)
   tempString=tempString.Substring(0,20);
else
   {
     tempString = tempString.PadRight(20); //use this if you need space after the word
            tempString = tempString.PadLeft(20); //use this if you need space before the word
   }
sw.Write(tempString);


更新:根据op的评论:

您可以使用Padding在您的实际字符串后附加一个空字符串。 C#提供了两个填充选项,例如右填充和左填充。


  PadRight在字符串的右边添加空格。 PadLeft同时添加
  靠左。这些方法使文本更易于阅读。填充字符串
  在开头或结尾添加空格或其他字符。任何
  字符可用于填充。

10-08 12:45