您的位置:首页 > 编程语言 > C#

c# 导出到Excel

2010-11-25 12:08 183 查看
VS2008导出Excel2007

 

引用:Microsoft.Office.Interop.Excel

代码:

 

public class ExportToEXCEL
{
public void ExportTo(SaveFileDialog saveFileDialog1, DevComponents.DotNetBar.ButtonX button3, DataGridView dataGridView1, GroupBox groupBox2, ProgressBar progressBar1)
{
bool b1 = true; //导出数据是否出错
double n1 = 0; //进度条显示
string s1 = ""; //进度条显示
string sSaveFileName; //EXCEL文件名
saveFileDialog1.Reset();
saveFileDialog1.DefaultExt = "xlsx";
saveFileDialog1.Filter = "xlsx|*.xlsx";
saveFileDialog1.ShowDialog();
sSaveFileName = saveFileDialog1.FileName;
if (string.IsNullOrEmpty(sSaveFileName) == false)
{
try
{
button3.Enabled = false;
progressBar1.Enabled = true;
if (dataGridView1.Rows.Count > 0)
{
groupBox2.Text = "请等待,正在导出数据至EXCEL... ...";
groupBox2.Refresh();
Microsoft.Office.Interop.Excel.Application Excel1 = new Microsoft.Office.Interop.Excel.Application();
Excel1.Application.Workbooks.Add(true);
Excel1.Visible = false;
for (int i = 0; i < dataGridView1.ColumnCount; i++)
{
if (dataGridView1.Columns[i].Visible == true)
Excel1.Cells[1, i + 1] = dataGridView1.Columns[i].HeaderText;
}
for (int i1 = 0; i1 < dataGridView1.RowCount; i1++)
{
Application.DoEvents();
n1 = (double)(i1 + 1) / dataGridView1.RowCount * 100;
progressBar1.Value = (int)n1;
s1 = progressBar1.Value.ToString() + "%";
groupBox2.Text = "完成百分比:" + s1;
for (int i2 = 0; i2 < dataGridView1.ColumnCount; i2++)
{
if (dataGridView1.Columns[i2].Visible == true)
Excel1.Cells[i1 + 2, i2 + 1] = "'" + dataGridView1.Rows[i1].Cells[i2].Value;
}
}
//如果文件存在,则先删除该文件
if (System.IO.File.Exists(sSaveFileName))
{
System.IO.File.Delete(sSaveFileName);
}
Excel1.ActiveWorkbook.Close(true, sSaveFileName, System.Reflection.Missing.Value);
Excel1.Quit();
groupBox2.Text = "数据导出EXCEL完成";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
b1 = false;
}
finally
{
if (b1 == true)
MessageBox.Show("导出EXCEL文件成功完成", "Note", MessageBoxButtons.OK, MessageBoxIcon.Information);
button3.Enabled = true;
progressBar1.Enabled = false;
}
}
}
  

 

调用方式:           

ExportToEXCEL Exp = new ExportToEXCEL();

Exp.ExportTo(saveFileDialog1, buttonX6, dataGridView2,groupBox1,progressBar1);

2010-11-25
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息