OLEDB for EXCEL - Drop Table [SheetName $] - 不要删除工作表

Bal*_*ngh 2 c# oledb excel

我使用drop table [SheetName $]从excel中删除工作表.

这只是清除工作表的数据但不删除工作表.

我尝试过使用xls和xlsx.不适用于这两个版本!

OleDbConnection connection = new OleDbConnection();

try
{
connection.ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;Extended Properties='drop.xlsx";
connection.Open();
OleDbCommand command = new OleDbCommand("Drop Table [MySheetName_1$]", connection);
command.ExecuteNonQuery();
}
finally
{
connection.Close();
}
Run Code Online (Sandbox Code Playgroud)

任何帮助/指针赞赏!谢谢

IAm*_*rey 5

遗憾的是,您无法使用ADO.NET for Excel删除工作表.相反,您需要使用Excel Interop来执行此任务.实际DELETE语句的基本代码如下所示:

using MSExcel = Microsoft.Office.Interop.Excel;

private MSExcel._Application excel;
private MSExcel._Workbook workbook;
private MSExcel._Worksheet worksheet;
private MSExcel.Sheets sheet;

Excelapp.DisplayAlerts = false;
((Excel.Worksheet)workBook.Worksheets[3]).Delete();
Excelapp.DisplayAlerts = true;
Run Code Online (Sandbox Code Playgroud)

这是它看起来如何的基本概述.DisplayAlerts系列用于解决一些人删除工作表时遇到的问题.另请注意,您无法删除Excel文件中的最后一个工作表.如果你不看,这个问题会得到你.

以下是一些可以帮助您的链接:

关于在Excel中删除工作表的MSDN

发表讨论使用ADO.NET在Excel中删除工作表的可能性

关于使用Interop在Excel中删除工作表的问题