0
我想在C#中創建一個應用程序,用戶可以手動填充行數據,然後按導出按鈕,這會將行導出到文本文件中。c#導出到文本文件爲導出文件指定列寬
我可以使用下面的代碼獲取要導出的文件,但是我希望每個列在導出文件時都具有特定的寬度。
我該怎麼做?
private void Form1_Load(object sender, EventArgs e)
{
//If you manually add rows to a DataGridView, you must disable the
//AllowUserToAddRows function. The function can be enabled after
//you have added the rows.
dataGridView1.AllowUserToAddRows = false;
//The code below adds Columns to the DataGridView control
DataGridViewColumn colHold = new DataGridViewTextBoxColumn();
colHold.Name = "col1";
colHold.HeaderText = "FIELD1";
dataGridView1.Columns.Add(colHold);
colHold = new DataGridViewTextBoxColumn();
colHold.Name = "col2";
colHold.HeaderText = "FIELD2";
dataGridView1.Columns.Add(colHold);
colHold = new DataGridViewTextBoxColumn();
colHold.Name = "col3";
colHold.HeaderText = "FIELD3";
dataGridView1.Columns.Add(colHold);
colHold = new DataGridViewTextBoxColumn();
colHold.Name = "col4";
colHold.HeaderText = "FIELD4";
dataGridView1.Columns.Add(colHold);
//The code below adds rows and fills cells with values to be exported.
dataGridView1.Rows.Add();
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = "1".PadRight(20);
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = "2";
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = "3";
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = "4";
dataGridView1.Rows.Add();
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[0].Value = "5";
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[1].Value = "6";
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[2].Value = "7";
dataGridView1.Rows[dataGridView1.Rows.Count - 1].Cells[3].Value = "8";
}
private void button1_Click(object sender, EventArgs e)
{
//This line of code creates a text file for the data export.
System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\TextFile.csv"); try
{
string sLine = "";
//This for loop loops through each row in the table
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
//This for loop loops through each column, and the row number
//is passed from the for loop above.
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
//A comma is added as a text delimiter in order
//to separate each field in the text file.
//You can choose another character as a delimiter.
sLine = sLine + " ";
}
}
//The exported text is written to the text file, one line at a time.
file.WriteLine(sLine);
sLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Exportlete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (System.Exception err)
{
System.Windows.Forms.MessageBox.Show(err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
file.Close();
}
}
private void button2_Click(object sender, EventArgs e)
{
}
}
你問有關導出但你顯示網格代碼?網格旨在*顯示*表格數據,而不是保存CSV或固定寬度文件 –
csv文件中的列寬? – mybirthname