我正在创建一个Windows应用程序,我将数据从DataGridView导出到Excel。问题是当它导出数据格式更改时,例如网格中的数据格式为dd/mm/yyyy
但是它导出为dd/mm/yyyy tt:mm
并且有些像2.10
这样的数字会出现在Excel上2.1
:
private void button4_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Excel Documents (*.csv)|*.csv";
sfd.FileName = "GE.csv";
if (sfd.ShowDialog() == DialogResult.OK)
{
//ToCsV(dataGridView1, @"c:\export.xls");
ToCsV(dataGridView2, sfd.FileName); // Here dataGridview1 is your grid view name
}
textBox3.Text = sfd.FileName;
button5.Visible = true;
}
private void ToCsV(DataGridView dGV, string filename)
{
string stOutput = "";
// Export titles:
string sHeaders = "";
for (int j = 0; j < dGV.Columns.Count; j++)
sHeaders = sHeaders.ToString() + Convert.ToString(dGV.Columns[j].HeaderText) + "\t";
stOutput += sHeaders + "\r\n";
// Export data.
for (int i = 0; i < dGV.RowCount - 1; i++)
{
string stLine = "";
for (int j = 0; j < dGV.Rows[i].Cells.Count; j++)
stLine = stLine.ToString() + Convert.ToString(dGV.Rows[i].Cells[j].Value) + "\t";
stOutput += stLine + "\r\n";
}
Encoding utf16 = Encoding.GetEncoding(1254);
byte[] output = utf16.GetBytes(stOutput);
FileStream fs = new FileStream(filename, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
bw.Write(output, 0, output.Length); //write the encoded file
bw.Flush();
bw.Close();
fs.Close();
}
有什么方法吗?
更新:
我已经将数据库上的日期归档更改为varchar并且它有效,但是仍然数字会丢失最后一个decimel如果它为零,我试图将其提取到txt文件它出来的零但是当我打开使用excel的文本会丢失零