I have a datagridview
that has some records.I have to export this record in .txt file format.When it export to .txt file ,records are not in proper format as picture attached
i have write some code for exporting to .txt file
string FileName = CurrentUserContext.CurrentEnterprise.FSaveReportTo+"\\" + fExpFile.strFileName + ".txt";
bool IncludeColHeaders = fExpFile.includeHeaders;
StringBuilder sb = new StringBuilder();
if (Company != null)
{
sb.AppendLine("Company: " + Company.FName);
}
sb.AppendLine("Bank: " + Bank.FBankName + "\t" + Bank.FBankNo);
sb.AppendLine("Account: " + Bank.FAccountName + "\t" + Bank.FAccountNo);
sb.AppendLine("\n");
string strColumnHeaders = null;
int ColumnCount = this.dgvCheckdetails.ColumnCount;
if (IncludeColHeaders)
{
for (int j = 0; j <= ColumnCount - 2; j++)
{
if (j == 3 || j == 5)
{
strColumnHeaders += "\t\t";
}
if (j != 4)
{
strColumnHeaders += dgvCheckdetails.Columns[j].HeaderText + "\t";
}
}
sb.AppendLine(strColumnHeaders);
}
int rowcount = dgvCheckdetails.Rows.Count;
string strRow;
for (int i = 0; i <= rowcount - 1; i++)
{
strRow = null;
for (int j = 0; j <= ColumnCount - 2; j++)
{
if (j != 4)
strRow += Convert.ToString(dgvCheckdetails.Rows[i].Cells[j].Value) + "\t";
}
sb.AppendLine(strRow);
}
File.WriteAllText(FileName, sb.ToString());
MessageBox.Show(CultureManager.GetMessageString("Export_Data_Successfully_Exported"));
How can i align the columns in .txt file which is exported from datagridview
?
The problem lies in your code to write the lines using "\\t" to attempt to align the columns. The correct way to do this would be to using padding in place of tabs. Tabs will cause things to shift unexpected depending on the length of data whereas the padding will account for that and scale accordingly.
Check out this similar SO post that explains a bit about padding:
Pad left or right with string.format
or this MSDN link:
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.