using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Word = Microsoft.Office.Interop.Word;
using System.Threading;
using office = Microsoft.Office.Core;
using System.Reflection;
using System.Data.OleDb;
using System.Data;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
txtOpenPath.Text = Server.MapPath("~/File/excel.xls");//初始化文件打开路径
BindDropDownList();
}
}
protected void btnDel_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.ApplicationClass();//实例化Excel对象
object missing = Missing.Value;//获取缺少的object类型值
//打开指定的Excel文件
Microsoft.Office.Interop.Excel.Workbook workbook = excel.Application.Workbooks.Open(txtOpenPath.Text, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing, missing);
((Microsoft.Office.Interop.Excel.Worksheet)workbook.Sheets[ddlSheetName.Text]).Delete();//删除选择的工作表
Response.Write("<script>alert('工作表删除成功!');</script>");
excel.Application.DisplayAlerts = false;//不显示提示对话框
workbook.Save();//保存工作表
BindDropDownList();//对下拉列表进行数据绑定
System.Diagnostics.Process[] excelProcess = System.Diagnostics.Process.GetProcessesByName("EXCEL");//实例化进程对象
foreach (System.Diagnostics.Process p in excelProcess)
{
p.Kill();//关闭进程
}
}
private void BindDropDownList()//对下拉列表进行数据绑定
{
ddlSheetName.Items.Clear();//清空下拉列表项
//连接Excel数据库
OleDbConnection olecon = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + txtOpenPath.Text + ";Extended Properties=Excel 8.0");
olecon.Open();//打开数据库连接
System.Data.DataTable DTable = olecon.GetSchema("Tables");//实例化表对象
DataTableReader DTReader = new DataTableReader(DTable);//实例化表读取对象
while (DTReader.Read())//循环读取
{
ddlSheetName.Items.Add(DTReader["Table_Name"].ToString().Replace('$', ' ').Trim());//将工作表名添加到下拉列表中
}
DTable = null;//清空表对象
DTReader = null;//清空表读取对象
olecon.Close();//关闭数据库连接
ddlSheetName.SelectedIndex = 0;//设置下拉列表默认选项为第一项
}
}
EXCEL:删除EXCEL文件中指定的工作表
最新推荐文章于 2024-11-14 09:59:03 发布