step1:单击保存数据按钮,弹出另存为的窗体,选择目标文件夹
step2:若目标文件夹以存在相同文件,则覆盖原文件。若没有,则新建
step3:在目标文件夹中打开导出的文件,是excel格式
代码如下:
//选择文件夹
private void button1_Click(object sender, EventArgs e)
{
//1、打开对话框,选择将报表文件输出的位置
/
string fileName = "";
SaveFileDialog dlg = new SaveFileDialog();
dlg.FileName = "知识库";
dlg.AddExtension = true;
dlg.Filter = "Excel 文件(*.xls)|*.xls";
if (dlg.ShowDialog() == DialogResult.OK)
{
fileName = dlg.FileName;
}
else
{
return;
}
System.Windows.Forms.Application.DoEvents();
///
//2、将模板文件另存为excel文件,保存在输出位置
///
//如果存在当前文件,则先删除原文件。
try
{
if (File.Exists(fileName))
{
File.Delete(fileName);
}
}
catch
{
MessageBox.Show("你要输出的文件正在被打开,请先关闭该输出文件,再输出报表!", "系统提示");
return;
}
String templatePath = System.AppDomain.CurrentDomain.BaseDirectory;//获得基目录
templatePath += "//report/report.xls";//excel模板的路径
if (!File.Exists(fileName))
{
File.Copy(templatePath, fileName, true);
}
///
//3.输出报表
output(fileName); ///如果不单独写个方法。导出数据后,进程不关闭。
GC.Collect();//垃圾回收机制
MessageBox.Show("导出报表成功!");
}
//输出报表
private void output(String fileName)
{
//3.1、创建excel对象,获得指定sheet位置。
//创建excel输出对象
Excel.Application excel = new Excel.Application();
Excel.Workbooks workbooks = excel.Workbooks;
Excel.Workbook workbook = workbooks.Open(@fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
Excel.Worksheet ws = null;//要输出的excel,sheet页
//选择在sheet 1输出内容
ws = (Excel.Worksheet)workbook.Worksheets[1];//设定第N张表
/
//3.2 开始在excel文件中写输出内容
/
ArrayList list = readList();//获得listview填充数据的方法
String[] data = new String[3];//创建临时数组
int count = list.Count;
for (int i = 0; i < count; i++)
{
int rownum = i + 2;//从第二行开始写数据(模板页第一行是标题)
WorkBook book = (WorkBook)list[i];
data[0] = book.title;
data[1] = book.content;
data[2] = book.createtime;
//创建excel即将要输出的范围区域
Excel.Range range = ws.get_Range("A" + rownum, "C" + rownum);//从A[rownum]到C[rownum]
//将数组的数据写入excel范围区域
range.Value2 = data;
}
//保存
workbook.Save();
//
//3.3 关闭excel,并清空内存,关闭进程
//
workbook.Close(Type.Missing, Type.Missing, Type.Missing);
workbooks.Close();
excel.Quit();
ws = null;
workbook = null;
workbooks = null;
excel = null;
GC.Collect();
//
}