日期:2014-05-18  浏览次数:20738 次

C#导出excel
在C#中导出excel时,时间为空时导出来成“##########”显示,如何让其显示就为空?

------解决方案--------------------
调用这个方法可以实现

public static void ExportDataGridViewToExcel(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.Title = "导出Excel文件到";
saveFileDialog.OverwritePrompt = true;
DateTime now = DateTime.Now;
saveFileDialog.FileName = now.Year.ToString().PadLeft(2)
+ now.Month.ToString().PadLeft(2, '0')
+ now.Day.ToString().PadLeft(2, '0') + "-"
+ now.Hour.ToString().PadLeft(2, '0')
+ now.Minute.ToString().PadLeft(2, '0')
+ now.Second.ToString().PadLeft(2, '0');

DialogResult result = saveFileDialog.ShowDialog();
if (result == DialogResult.OK)
{
Stream myStream;
myStream = saveFileDialog.OpenFile();
StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
string str = "";
try
{
//写标题
for (int i = 0; i < dataGridview1.ColumnCount; i++)
{
if (i > 0)
{
str += "\t";
}
str += dataGridview1.Columns[i].HeaderText;
}

sw.WriteLine(str);
//写内容
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";
}
if (dataGridview1.Rows[j].Cells[k].Value == null)
{
tempStr += "";
}
else
{
tempStr += Convert.ToString(dataGridview1.Rows[j].Cells[k].Value.ToString());
}

}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
MessageBox.Show("数据导出成功!", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);

}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
}
------解决方案--------------------
探讨

调用这个方法可以实现

public static void ExportDataGridViewToExcel(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialo……