请问使用这个方法导出EXCEL能否保证数据的完整性?
//datagridview转excel的方法
public void ExportDataGridViewToExcel(DataGridView dataGridview1)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Execl files (*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "导出Excel文件到";
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');
saveFileDialog.ShowDialog();
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";
}
tempStr += dataGridview1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
sw.Close();
myStream.Close();
MessageBox.Show("导出成功");
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
请问通过字节流把DataGridView数据保存成EXCEL能否保证EXCEL数据完整性?既然这个函数都可以导出EXCEL.
那么就没必要使用 Excel.Application excel = new Excel.Application(); 导出数据了,但是由于这个函数
之前一直没有使用过,不知道在使用过程中是否有问题,请使用过这个方法的同行解答一下,谢谢
------解决方案--------------------
好像在 sw.Close();之前要加一句 sw.Flush(); 确保数据全部写完