How can I delete the default sheets Sheet1, Sheet2 and Sheet3 in Excel, when I use XLSWRITE?
71 次查看(过去 30 天)
显示 更早的评论
I would like to delete the default sheets Sheet1, Sheet2 and Sheet3 in Excel, when I use XLSWRITE.
采纳的回答
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.
0 个评论
更多回答(1 个)
Pruthvi G
2020-4-13
Download Link :: https://in.mathworks.com/matlabcentral/fileexchange/71329-delete-excel-workbook-sheets-sheet-1-delete-using-matlab
%%**********************************************************************************************************
% 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'})
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Spreadsheets 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!