excel导出功能原型

本篇博客是记录自己实现的excel导出功能原型,下面我将简单介绍本原型:

这是我自制的窗体,有一个ListView和一个Button(导出)控件。

这是我在网上找到了使用exel需要引用的库。

1
2
3
4
5
6
7
8
9
10
11
using Microsoft.Office.Core;
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

然后我便开始了对这个原型的假设与测试,我首先把ListView中的列标题,和一行666的假数据写到ListView里面。

  然后开始运行程序,此时出现以下画面:

点击导出按钮,得到excel表格,并可以选择存到指定目录下或默认路径下。

其核心代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private void button1_Click(object sender, EventArgs e)
{
    Excelex ee = new Excelex();
    ee.Create();
    ee.ws = ee.AddSheet("第一周");
    //循环保存写入数据
    ee.SetCellValue("第一周", 1, 1, "日期");
    ee.SetCellValue("第一周", 1, 2, "类别");
    ee.SetCellValue("第一周", 1, 3, "任务");
    ee.SetCellValue("第一周", 1, 4, "开始时间");
    ee.SetCellValue("第一周", 1, 5, "结束时间");
    ee.SetCellValue("第一周", 1, 6, "中断时间");
    ee.SetCellValue("第一周", 1, 7, "净时间");
    ee.SetCellValue("第一周", 1, 8, "备注");
    for (int i = 0; i < listView1.Items.Count; i++)
    {
        for (int j = 0; j < 8; j++)
        {
            ee.SetCellValue("第一周", i + 2, j + 1, listView1.Items[i].SubItems[j].Text);
        }
    }
    ee.app.Visible = true;//用excel打开,显示出来。
    ee.SaveAs("F:\\WPS\\newg.xls");
    MessageBox.Show("保存成功!请在****查看!");
    ee.Close();
}
1
2
3
4
5
6
//创建一个Microsoft.Office.Interop.Excel对象<br>     public void Create()
        {
            app = new Microsoft.Office.Interop.Excel.Application();
            wbs = app.Workbooks;
            wb = wbs.Add(true);
        }<br>
1
2
3
4
5
//ws:要设值的工作表的名称 X行Y列 value 值<br>     public void SetCellValue(string ws, int x, int y, object value)
        {
  
            GetSheet(ws).Cells[x, y] = value;
        }  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//文档另存为
        public bool SaveAs(object FileName)
         
        {
            try
            {
                wb.SaveAs(FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
                return true;
            }
 
            catch (Exception ex)
            {
                return false;
 
            }
        }

 

posted @   刘耀泽  阅读(1069)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示