今天vs2010c#开发做datagridview导出Excel文件时,发现一个问题,和大家探讨一下:
第一种方式:写流的方式
private void button_Excel_Click(object sender, EventArgs e)
{
if (dataGridView1.Tag.ToString() == "1")
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Microsoft Office Execl 工作薄(*.xls)|*.xls";
saveFileDialog.FilterIndex = 0;
saveFileDialog.RestoreDirectory = true;
saveFileDialog.CreatePrompt = true;
saveFileDialog.Title = "Export Excel File To";
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 < this.dataGridView1.ColumnCount; i++)
{
if (i > 0)
{
str += " ";
}
str += this.dataGridView1.Columns[i].HeaderText;
}
sw.WriteLine(str);
//写内容
for (int j = 0; j < this.dataGridView1.Rows.Count; j++)
{
string tempStr = "";
for (int k = 0; k < this.dataGridView1.Columns.Count; k++)
{
if (k > 0)
{
tempStr += " ";
}
tempStr += this.dataGridView1.Rows[j].Cells[k].Value.ToString();
}
sw.WriteLine(tempStr);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
finally
{
sw.Close();
myStream.Close();
}
}
else
{
MessageBox.Show("请先转换格式,再导出excel文件!", "提示");
}
}
这种方式也能导出excel文件,不过是假的,当你打开之后再关闭时,会提示你,另存为新的excel文件,所以比较烦人。
另外,程序运行完后,会提示:未将对象引用设置到对象的实例;
应该是“ tempStr += this.dataGridView1.Rows[j].Cells[k].Value.ToString();”这行,,不知道什么原因。
基于以上原因,程序中没有采用这个方式。
第二种方式:新建excel表格,需要添加相应的引用;
private void button_Excel_Click(object sender, EventArgs e)
{
if (dataGridView1.Tag.ToString() == "1")
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook workbook;
Microsoft.Office.Interop.Excel.Worksheet worksheet;
excel.Visible = true; //是Excel可见
workbook = excel.Workbooks.Add(XlWBATemplate.xlWBATWorksheet);
worksheet = (Worksheet)workbook.Worksheets[1];
System.Data.DataTable ecpTable = null;
ecpTable = (System.Data.DataTable)dataGridView1.DataSource;
for (int r = 0; r < ecpTable.Rows.Count; r++)
{
for (int i = 0; i < ecpTable.Columns.Count; i++)
{
worksheet.Cells[r + 1, i + 1] = ecpTable.Rows[r][i].ToString();
}
}
}
else
{ MessageBox.Show("请先转换格式,再导出excel文件!", "提示"); }
}
这种方式比较成功,你能看到导入的数据。最后采用了这种方式。