当前位置:网站首页>Go exceed API source code reading (VI) -- deletesheet (sheet string)
Go exceed API source code reading (VI) -- deletesheet (sheet string)
2022-07-26 05:16:00 【ReganYue】
Go-Excelize API Source code reading ( 6、 ... and )—— DeleteSheet(sheet string)
Open source star picking program (WeOpen Star) By Tengyuan society 2022 A new project launched in , Designed to provide growth incentives for open source people , Provide growth support for open source projects , Help developers better understand open source , Cross the gap faster , Participate in the specific contribution and practice of open source .
Whether you are open source Mengxin , Or veterans who want to participate more deeply in open source contributions , Follow “ Open source star picking program ” Start your open source journey , From a learning note 、 To the submission of a piece of code , Keep tapping your potential , Eventually grow into an open source community “ Blazing Star ”.
We will be with you , Explore more possibilities !
Project address : WeOpen-Star:https://github.com/weopenprojects/WeOpen-Star
One 、Go-Excelize brief introduction
Excelize yes Go Language written for operation Office Excel Document base library , be based on ECMA-376,ISO/IEC 29500 international standard . You can use it to read 、 Written by Microsoft Excel 2007 Spreadsheet documents created by and above . Support XLAM / XLSM / XLSX / XLTM / XLTX And so on , Highly compatible with styles 、 picture ( surface )、 PivotTable 、 Slicer and other complex components of the document , And provide streaming reading and writing API, For workbooks that contain large amounts of data . It can be applied to various report platforms 、 Cloud computing 、 Edge computing and other systems . Required to use this class library Go The language is 1.15 Or later .
Two 、DeleteSheet(sheet string)
func (f *File) DeleteSheet(sheet string)
Delete the specified worksheet according to the given worksheet name , Use this method with caution , This will affect the formula associated with the deleted worksheet 、 quote 、 Chart and other elements . If other components refer to the values on the deleted worksheet , Will cause an error , It will even cause the workbook to fail to open . When the workbook contains only one worksheet , Invalid call to this method .
func (f *File) DeleteSheet(name string) {
if f.SheetCount == 1 || f.GetSheetIndex(name) == -1 {
return
}
sheetName := trimSheetName(name)
wb := f.workbookReader()
wbRels := f.relsReader(f.getWorkbookRelsPath())
activeSheetName := f.GetSheetName(f.GetActiveSheetIndex())
deleteLocalSheetID := f.GetSheetIndex(name)
deleteAndAdjustDefinedNames(wb, deleteLocalSheetID)
for idx, sheet := range wb.Sheets.Sheet {
if !strings.EqualFold(sheet.Name, sheetName) {
continue
}
wb.Sheets.Sheet = append(wb.Sheets.Sheet[:idx], wb.Sheets.Sheet[idx+1:]...)
var sheetXML, rels string
if wbRels != nil {
for _, rel := range wbRels.Relationships {
if rel.ID == sheet.ID {
sheetXML = f.getWorksheetPath(rel.Target)
rels = "xl/worksheets/_rels/" + strings.TrimPrefix(f.sheetMap[sheetName], "xl/worksheets/") + ".rels"
}
}
}
target := f.deleteSheetFromWorkbookRels(sheet.ID)
f.deleteSheetFromContentTypes(target)
f.deleteCalcChain(sheet.SheetID, "")
delete(f.sheetMap, sheet.Name)
f.Pkg.Delete(sheetXML)
f.Pkg.Delete(rels)
f.Relationships.Delete(rels)
f.Sheet.Delete(sheetXML)
delete(f.xmlAttr, sheetXML)
f.SheetCount--
}
f.SetActiveSheet(f.GetSheetIndex(activeSheetName))
}
if f.SheetCount == 1 || f.GetSheetIndex(name) == -1 {
return
}
This code is to ensure that when the workbook contains only one worksheet , Or it is invalid to call this method when the name of the worksheet is incorrect .
func (f *File) GetSheetIndex(name string) int {
for index, sheet := range f.GetSheetList() {
if strings.EqualFold(sheet, trimSheetName(name)) {
return index
}
}
return -1
}
The above code shows : When the of the worksheet is not in the worksheet list GetSheetIndex return -1.
sheetName := trimSheetName(name) The function of is to get the name of the worksheet .
func trimSheetName(name string) string {
if strings.ContainsAny(name, ":\\/?*[]") || utf8.RuneCountInString(name) > 31 {
r := make([]rune, 0, 31)
for _, v := range name {
switch v {
case 58, 92, 47, 63, 42, 91, 93: // replace :\/?*[]
continue
default:
r = append(r, v)
}
if len(r) == 31 {
break
}
}
name = string(r)
}
return name
}
It's not hard to see. , This API The function of is to cut \/?*[] These content .
wb := f.workbookReader()
wbRels := f.relsReader(f.getWorkbookRelsPath())
workbookReader Get the deserialized workbook.xml Structure pointer .relsReader obtain xl/worksheets/_rels/sheet%d.xml.rels Deserialized structure pointer .
activeSheetName := f.GetSheetName(f.GetActiveSheetIndex())
deleteLocalSheetID := f.GetSheetIndex(name)
deleteAndAdjustDefinedNames(wb, deleteLocalSheetID)

GetActiveSheetIndex Provides a function to get the active worksheet index of the spreadsheet .
If the active worksheet is not found , Will return an integer 0.
About ActiveSheet The content of can be found in Microsoft documentation :
Workbook.ActiveSheet attribute (Excel) | Microsoft Docs
https://docs.microsoft.com/zh-cn/office/vba/api/excel.workbook.activesheet
activeSheetName Is the name of the active worksheet ,deleteLocalSheetID Is the current worksheet to delete ID.
deleteAndAdjustDefinedNames Through the given worksheet ID Delete and adjust the names defined in the workbook .
func deleteAndAdjustDefinedNames(wb *xlsxWorkbook, deleteLocalSheetID int) {
if wb == nil || wb.DefinedNames == nil {
return
}
for idx := 0; idx < len(wb.DefinedNames.DefinedName); idx++ {
dn := wb.DefinedNames.DefinedName[idx]
if dn.LocalSheetID != nil {
localSheetID := *dn.LocalSheetID
if localSheetID == deleteLocalSheetID {
wb.DefinedNames.DefinedName = append(wb.DefinedNames.DefinedName[:idx], wb.DefinedNames.DefinedName[idx+1:]...)
idx--
} else if localSheetID > deleteLocalSheetID {
wb.DefinedNames.DefinedName[idx].LocalSheetID = intPtr(*dn.LocalSheetID - 1)
}
}
}
}
among , The following code is cleverly used :
for idx, sheet := range wb.Sheets.Sheet {
if !strings.EqualFold(sheet.Name, sheetName) {
continue
}
wb.Sheets.Sheet = append(wb.Sheets.Sheet[:idx], wb.Sheets.Sheet[idx+1:]...)
var sheetXML, rels string
if wbRels != nil {
for _, rel := range wbRels.Relationships {
if rel.ID == sheet.ID {
sheetXML = f.getWorksheetPath(rel.Target)
rels = "xl/worksheets/_rels/" + strings.TrimPrefix(f.sheetMap[sheetName], "xl/worksheets/") + ".rels"
}
}
}
target := f.deleteSheetFromWorkbookRels(sheet.ID)
f.deleteSheetFromContentTypes(target)
f.deleteCalcChain(sheet.SheetID, "")
delete(f.sheetMap, sheet.Name)
f.Pkg.Delete(sheetXML)
f.Pkg.Delete(rels)
f.Relationships.Delete(rels)
f.Sheet.Delete(sheetXML)
delete(f.xmlAttr, sheetXML)
f.SheetCount--
}
This code is to delete sheetName The corresponding one sheet, The specific details will not be detailed .
f.SetActiveSheet(f.GetSheetIndex(activeSheetName)) Just continue to set up the active worksheet , It should be the previous activity table .
3、 ... and 、 Conclusion
This is Lao Yue , This is a Go Interpretation of language related source code Chapter 6 , I'll keep trying , Bring you more similar articles , Please give me your advice .
边栏推荐
- Week 6 Learning Representation: Word Embedding (symbolic →numeric)
- C语言详解系列——函数的认识(3)形参,实参,嵌套调用和链式访问
- ABAP语法学习(ALV)
- Week 6 Learning Representation: Word Embedding (symbolic →numeric)
- YOLOv5执行全过程----目录
- Shell read read console input, use of read
- NPM operation instruction
- 测试用例评审如何开展
- LeetCode链表问题——206.反转链表(一题一文学会链表)
- Annotation @autowired how to assemble automatically
猜你喜欢

Excel VBA: summarize calculation output results by date (SUMIF)

Mysql优化

Chinese character style transfer --- learn the conversion and generation of one to many programmed Chinese characters through generation confrontation network

OD-Paper【1】:Rich feature hierarchies for accurate object detection and semantic segmentation

Use flutter to adjust a color filter for the picture of my little sister

How many holes have you stepped on in BigDecimal?

Earth system model (cesm) practical technology

第二讲 初识SLAM

Improve reduce parallelism in shuffle operation

遥感、GIS和GPS技术在水文、气象、灾害、生态、环境及卫生等领域中的应用
随机推荐
OD-Paper【1】:Rich feature hierarchies for accurate object detection and semantic segmentation
Nacos registry
Alibaba three sides: how to solve the problems of MQ message loss, duplication and backlog?
新人如何做好功能测试,学会这几项够用了
35. Search the insertion position
Unity scene jump script
Embedded sharing collection 21
DOM event flow event bubble event capture event delegate
Redis过期删除策略和内存淘汰策略
C语言详解系列——函数的认识(4)函数的声明与定义,简单练习题
mysql如果计算本月变动/本月增幅/同比变动/同比增幅?
家居vr全景展示制作提高客户转化
MySQL eight knowledge points: from getting started to deleting the database
第二讲 初识SLAM
Excel VBA: realize automatic drop-down filling formula to the last line
Trend of the times - the rise of cloud native databases
no networks found in /etc/cni/net.d
YOLOv5执行全过程----目录
Excel VBA: summarize calculation output results by date (SUMIF)
【Leetcode】493. Reverse Pairs