当前位置:网站首页>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 .
边栏推荐
- Meta analysis [whole process, uncertainty analysis] method based on R language and meta machine learning
- MySQL基础学习
- Excel VBA: summarize calculation output results by date (SUMIF)
- 推荐12个免费查找文献的学术网站,建议点赞、收藏!
- When AQS wakes up the thread, I understand why it traverses from the back to the front
- flex布局原理及常见的父项元素
- I talked with the interviewer about MySQL optimization in five dimensions
- Distance between bus stops: simple simulation problem
- 10. 正则表达式匹配
- C语言详解系列——函数的认识(3)形参,实参,嵌套调用和链式访问
猜你喜欢

C语言-指针进阶

Learn to map with nature medicine -- complex heat map

LeetCode链表问题——203.移除链表元素(一题一文学会链表)

Textfield and password input box that are more flexible and easy to use in compose

推荐12个免费查找文献的学术网站,建议点赞、收藏!

I talked with the interviewer about MySQL optimization in five dimensions

MODFLOW flex, GMS, FEFLOW, hydraus practical application

Redis过期删除策略和内存淘汰策略
![[acwing] 1268. Simple questions](/img/f3/7eeae566dd74d77cf6f8b4640e4f29.png)
[acwing] 1268. Simple questions

Compilation method of flood control evaluation report and flood modeling under the new guidelines
随机推荐
LeetCode链表问题——206.反转链表(一题一文学会链表)
Princeton calculus reader 02 Chapter 1 -- composition of functions, odd and even functions, function images
517. 超级洗衣机
[Luogu] p1383 advanced typewriter
JVM Lecture 2: class loading mechanism
如何优雅的复现YOLOv5官方历程(二)——标注并训练自己的数据集
[weekly translation go] how to write your first program with go
mysql如果计算本月变动/本月增幅/同比变动/同比增幅?
Unnamed Article 33
【pytorch】torch1.8.1安装、查看torch版本、GPU是否可用
Ansible中常用的模块
Webassembly 01 basic information
Use flutter to adjust a color filter for the picture of my little sister
NPM operation instruction
YOLOv5执行全过程----目录
35. 搜索插入位置
Okaleido launched the fusion mining mode, which is the only way for Oka to verify the current output
C语言实现发牌功能基本方法
手把手教你用代码实现SSO单点登录
SAP报表开发步骤