How can I delete the default sheets Sheet1, Sheet2 and Sheet3 in Excel, when I use XLSWRITE?

73 ビュー (過去 30 日間)
I would like to delete the default sheets Sheet1, Sheet2 and Sheet3 in Excel, when I use XLSWRITE.

採用された回答

MathWorks Support Team
MathWorks Support Team 2009 年 8 月 12 日
You can delete the sheets that get created automatically by Excel when you use XLSWRITE with a new file name by using ActiveX functionality (Windows only).
Example:
excelFileName = 'Test.xls';
excelFilePath = pwd; % Current working directory.
sheetName = 'Sheet'; % EN: Sheet, DE: Tabelle, etc. (Lang. dependent)
% Open Excel file.
objExcel = actxserver('Excel.Application');
objExcel.Workbooks.Open(fullfile(excelFilePath, excelFileName)); % Full path is necessary!
% Delete sheets.
try
% Throws an error if the sheets do not exist.
objExcel.ActiveWorkbook.Worksheets.Item([sheetName '1']).Delete;
objExcel.ActiveWorkbook.Worksheets.Item([sheetName '2']).Delete;
objExcel.ActiveWorkbook.Worksheets.Item([sheetName '3']).Delete;
catch
; % Do nothing.
end
% Save, close and clean up.
objExcel.ActiveWorkbook.Save;
objExcel.ActiveWorkbook.Close;
objExcel.Quit;
objExcel.delete;
In this way, you will be able to delete the default sheets from the workbook. But as the workbook should at least contain one worksheet, you will not be able to delete the last remaining sheet. You can work around this by creating your own sheet first and then deleting the default sheets.

その他の回答 (1 件)

Pruthvi G
Pruthvi G 2020 年 4 月 13 日
%%**********************************************************************************************************
% Name : Delete_sheets_Excel
% Author : Pruthvi Raj G :: (9677066394 :: www.prudhvy.com )
% Version : Version 1.0 - 2011b Compactible
% Description : Deleting Excel Sheets required after writing data to Excel.
% Input : File_Name with path included , Sheet_name / Sheet_names.
% Date : 22-April-2019
%
% Examples : Delete_sheets_Excel('D:\Pruthvi\Test_file.xls',{'Sheet1','Sheet2'}) %To delete 2 sheets
% Delete_sheets_Excel('D:\Pruthvi\Test_file.xls','Sheet1')
% Delete_sheets_Excel('D:\Pruthvi\Test_file.xls') % Takes 'Sheet1' as Default
%************************************************************************************************************
Use the Below Lines of Code ::
Delete_sheets_Excel('D:\Pruthvi\Test_file.xls',{'Sheet1','Sheet2'})

カテゴリ

Help Center および File ExchangeSpreadsheets についてさらに検索

製品


リリース

R2007b

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by