导出Excel如何把数字转成文本呀?
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "Export Excel File";
saveFileDialog.ShowDialog();
if (saveFileDialog.FileName == "")
return;
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding(-0));
string str = "";
try
{
//寫dataGridView1表標題
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridView1.Columns[i].HeaderText.Trim();
}
sw.WriteLine(str);
//寫dataGridView1表內容
for (int j = 0; j < dataGridView1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += "\t";
}
tempStr += dataGridView1.Rows[j].Cells[k].Value;
//要增加對含數字的文字類,如身份証號
//.........欠對身份証號處理,以免在EXCEL打開時被自動轉數字
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
------解决方案--------------------
tempStr += dataGridView1.Rows[j].Cells[k].Value;
改成
tempStr += "=\"" + dataGridView1.Rows[j].Cells[k].Value + "\"";