--写入Excel表--
该例首先从数据库aq中读取学生信息表staq(参考数据库章节),然后将学生信息表中的数据写入Excel表格中
(1)在OfficeOperator类库项目的ExcelOperator类中定义索引器,用于获取Excel表格中的单元格,代码如下:
public Range this[object indexRow, object indexColumn]
{
get { return ExcelWorksheet.Cells[indexRow, indexColumn]; } //返回指定单元格
}
using Microsoft.Office.Interop.Excel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace OfficeOperator2
{
public class ExcelOperator
{
public Application ExcelApplication; //Excel应用对象
public Workbook ExcelWorkbook; //Excel工作簿对象
public Worksheet ExcelWorksheet; //Excel工作表对象
public ExcelOperator()//声明用于操作Excel的对象,并定义其构造函数
{
ExcelApplication = new Application(); //创建Application对象
// ExcelApplication.Visible = true; //创建完成后是否打开Excel
}
/// <summary>
/// 创建Excel表格
/// </summary>
public void CreateExcel()
{
ExcelWorkbook = ExcelApplication.Workbooks.Add(true); //添加工作簿
ExcelWorksheet = ExcelWorkbook.Worksheets[1] as Worksheet; //获取工作表
}
/// <summary>
/// 保存Excel表格
/// </summary>
/// <param name="fileName"></param>
public void SaveExcel(string fileName)
{
ExcelApplication.DisplayAlerts = false; //设置禁止弹出保存询问提示框
ExcelApplication.AlertBeforeOverwriting = false; //设置禁止弹出覆盖询问提示框
object FileName = fileName; //需要保存Excel文件的名称
object Password = ""; //打开Excel文档密码,少于16位
object WriteResPassword = ""; //修改Excel文档密码,小于16位
object ReadOnlyRecommended = false; //Excel以只读形式打开是否提示
object CreateBackup = false; //是否创建备份
ExcelWorkbook.SaveAs(FileName, Missing.Value, Password, WriteResPassword, ReadOnlyRecommended, CreateBackup, XlSaveAsAccessMode.xlNoChange);
}
/// <summary>
/// 退出Excel应用
/// </summary>
public void QuitExcel()