|
After I import the DataGridView data into Excel using the following method:
Because some of my field values are all digits and start with 0, Excel will treat them as numbers by default, which will remove the leading 0. Can you set all Excel cell types to text? ?
SaveFileDialog saveFileDialog = new SaveFileDialog ();
saveFileDialog.Filter = "Execl files (* .xls) | * .xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel file to";
saveFileDialog.ShowDialog ();
if (saveFileDialog.FileName! = "")
{
Stream myStream;
myStream = saveFileDialog.OpenFile ();
StreamWriter sw = new StreamWriter (myStream, System.Text.Encoding.GetEncoding ("gb2312"));
string str = "";
try
{
// write title
for (int i = 0; i <this.sc_madanDataGridView.ColumnCount; i ++)
{
if (i> 0)
{
str + = "\t";
}
str + = sc_madanDataGridView.Columns [i] .HeaderText;
}
sw.WriteLine (str);
// Write content
for (int j = 0; j <sc_madanDataGridView.Rows.Count; j ++)
{
string tempStr = "";
for (int k = 0; k <sc_madanDataGridView.Columns.Count; k ++)
{
if (k> 0)
{
tempStr + = "\t";
}
tempStr + = sc_madanDataGridView.Rows [j] .Cells [k] .FormattedValue.ToString ();
}
sw.WriteLine (tempStr);
}
sw.Close ();
myStream.Close ();
}
catch
{
MessageBox.Show (e.ToString ());
}
finally
{
sw.Close ();
myStream.Close ();
} |
|