lucky_sheet.go 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651
  1. package excel
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "github.com/tealeg/xlsx"
  7. "github.com/xuri/excelize/v2"
  8. "hongze/hz_crm_api/models/data_manage/request"
  9. "hongze/hz_crm_api/utils"
  10. "os"
  11. "reflect"
  12. "strconv"
  13. "strings"
  14. "time"
  15. )
  16. type LuckySheetDataBak struct {
  17. CalcChain []interface{} `json:"calcChain" description:"公式链"`
  18. CellData []LuckySheetCellData `json:"celldata" description:"单元格数据"`
  19. ChWidth int64 `json:"ch_width" description:"工作表区域的宽度"`
  20. Config struct {
  21. BorderInfo []struct {
  22. BorderType string `json:"borderType" description:""`
  23. Color string `json:"color" description:""`
  24. Range []struct {
  25. Column []int64 `json:"column" description:""`
  26. Row []int64 `json:"row" description:""`
  27. } `json:"range" description:""`
  28. RangeType string `json:"rangeType" description:""`
  29. Style string `json:"style" description:""`
  30. Value struct {
  31. B struct {
  32. Color string `json:"color" description:""`
  33. Style string `json:"style" description:""`
  34. } `json:"b" description:""`
  35. ColIndex int64 `json:"col_index" description:""`
  36. L struct {
  37. Color string `json:"color" description:""`
  38. Style string `json:"style" description:""`
  39. } `json:"l" description:""`
  40. R struct {
  41. Color string `json:"color" description:""`
  42. Style string `json:"style" description:""`
  43. } `json:"r" description:""`
  44. RowIndex int64 `json:"row_index" description:""`
  45. T struct {
  46. Color string `json:"color" description:""`
  47. Style string `json:"style" description:""`
  48. } `json:"t" description:""`
  49. } `json:"value" description:"" description:""`
  50. } `json:"borderInfo" description:""`
  51. Colhidden struct{} `json:"colhidden" description:""`
  52. Columnlen map[string]float64 `json:"columnlen" description:""`
  53. CustomHeight struct {
  54. Zero int64 `json:"0"`
  55. } `json:"customHeight" description:""`
  56. CustomWidth struct {
  57. Two int64 `json:"2" description:""`
  58. } `json:"customWidth" description:""`
  59. Merge struct{} `json:"merge" description:""`
  60. Rowlen map[string]float64 `json:"rowlen" description:""`
  61. } `json:"config" description:""`
  62. Data [][]struct {
  63. Ct struct {
  64. Fa string `json:"fa"`
  65. T string `json:"t"`
  66. } `json:"ct"`
  67. M string `json:"m"`
  68. V interface{} `json:"v"`
  69. } `json:"data" description:""`
  70. DataVerification struct{} `json:"dataVerification" description:""`
  71. Filter interface{} `json:"filter" description:""`
  72. FilterSelect interface{} `json:"filter_select" description:""`
  73. Hyperlink struct{} `json:"hyperlink" description:""`
  74. Images struct{} `json:"images" description:""`
  75. Index string `json:"index" description:""`
  76. JfgirdSelectSave []interface{} `json:"jfgird_select_save" description:""`
  77. LuckysheetAlternateformatSave []interface{} `json:"luckysheet_alternateformat_save" description:""`
  78. LuckysheetConditionformatSave []interface{} `json:"luckysheet_conditionformat_save" description:""`
  79. LuckysheetSelectSave []struct {
  80. Column []int64 `json:"column" description:""`
  81. ColumnFocus int64 `json:"column_focus" description:""`
  82. Height int64 `json:"height" description:""`
  83. HeightMove int64 `json:"height_move" description:""`
  84. Left int64 `json:"left" description:""`
  85. LeftMove int64 `json:"left_move" description:""`
  86. Row []int64 `json:"row" description:""`
  87. RowFocus int64 `json:"row_focus" description:""`
  88. Top int64 `json:"top" description:""`
  89. TopMove int64 `json:"top_move" description:""`
  90. Width int64 `json:"width" description:""`
  91. WidthMove int64 `json:"width_move" description:""`
  92. } `json:"luckysheet_select_save" description:"" description:""`
  93. LuckysheetSelectionRange []struct {
  94. Column []int64 `json:"column" description:""`
  95. Row []int64 `json:"row" description:""`
  96. } `json:"luckysheet_selection_range" description:""`
  97. RhHeight float64 `json:"rh_height" description:""`
  98. ScrollLeft float64 `json:"scrollLeft" description:""`
  99. ScrollTop float64 `json:"scrollTop" description:""`
  100. Status int64 `json:"status" description:""`
  101. Visibledatacolumn []int64 `json:"visibledatacolumn" description:""`
  102. Visibledatarow []int64 `json:"visibledatarow" description:""`
  103. ZoomRatio float64 `json:"zoomRatio" description:"sheet缩放比例"`
  104. }
  105. // LuckySheetData sheet表格数据
  106. type LuckySheetData struct {
  107. CellData []LuckySheetCellData `json:"celldata" description:"单元格数据"`
  108. ChWidth int64 `json:"ch_width" description:"工作表区域的宽度"`
  109. Config LuckySheetDataConfig `json:"config" description:""`
  110. //Index int `json:"index" description:"工作表索引"`
  111. RhHeight float64 `json:"rh_height" description:"工作表区域的高度"`
  112. ScrollLeft float64 `json:"scrollLeft" description:"左右滚动条位置"`
  113. ScrollTop float64 `json:"scrollTop" description:"上下滚动条位置"`
  114. Status int64 `json:"status" description:"激活状态"`
  115. VisibleDataColumn []int64 `json:"visibledatacolumn" description:"所有列的位置信息,递增的列位置数据,初始化无需设置"`
  116. VisibleDataRow []int64 `json:"visibledatarow" description:"所有行的位置信息,递增的行位置数据,初始化无需设置"`
  117. ZoomRatio float64 `json:"zoomRatio" description:"sheet缩放比例"`
  118. }
  119. // LuckySheetDataConfig sheet表单的配置
  120. type LuckySheetDataConfig struct {
  121. BorderInfo []LuckySheetDataConfigBorderInfo `json:"borderInfo" description:"边框"`
  122. Colhidden map[string]int64 `json:"colhidden" description:"隐藏列,示例值:\"colhidden\":{\"30\":0,\"31\":0}"`
  123. Columnlen map[string]float64 `json:"columnlen" description:"每个单元格的列宽"`
  124. //CustomHeight struct {
  125. // Zero int64 `json:"0"`
  126. //} `json:"customHeight" description:""`
  127. //CustomWidth struct {
  128. // Two int64 `json:"2" description:""`
  129. //} `json:"customWidth" description:""`
  130. Merge map[string]LuckySheetDataConfigMerge `json:"merge" description:"合并单元格"`
  131. Rowlen map[string]float64 `json:"rowlen" description:"每个单元格的行高"`
  132. }
  133. // LuckySheetDataConfigMerge 合并单元格设置
  134. type LuckySheetDataConfigMerge struct {
  135. Row int `json:"r" description:"行数"`
  136. Column int `json:"c" description:"列数"`
  137. Rs int `json:"rs" description:"合并的行数"`
  138. Cs int `json:"cs" description:"合并的列数"`
  139. }
  140. // LuckySheetDataConfigBorderInfo 单元格边框信息
  141. type LuckySheetDataConfigBorderInfo struct {
  142. BorderType string `json:"borderType" description:"边框类型 border-left | border-right | border-top | border-bottom | border-all | border-outside | border-inside | border-horizontal | border-vertical | border-none"`
  143. Color string `json:"color" description:"边框颜色 color: 16进制颜色值"`
  144. Range []struct {
  145. Column []int64 `json:"column" description:"行"`
  146. Row []int64 `json:"row" description:"列"`
  147. } `json:"range" description:"选区范围 range: 行列信息数组"`
  148. RangeType string `json:"rangeType" description:"选区 rangeType: range | cell "`
  149. Style string `json:"style" description:"边框粗细 style: 1 Thin | 2 Hair | 3 Dotted | 4 Dashed | 5 DashDot | 6 DashDotDot | 7 Double | 8 Medium | 9 MediumDashed | 10 MediumDashDot | 11 MediumDashDotDot | 12 SlantedDashDot | 13 Thick ,和aspose.cells的getLineStyle()的值对应的话,需要自己做个转换,参考 aspose.cells"`
  150. Value LuckySheetDataConfigBorderInfoCellValue `json:"value" description:"" description:"范围类型分单个单元格的数据"`
  151. }
  152. // LuckySheetDataConfigBorderInfoCellValue 单元格边框信息(范围类型为:单个单元格)
  153. type LuckySheetDataConfigBorderInfoCellValue struct {
  154. B LuckySheetDataConfigBorderInfoCell `json:"b" description:"下边框"`
  155. L LuckySheetDataConfigBorderInfoCell `json:"l" description:"左边框"`
  156. R LuckySheetDataConfigBorderInfoCell `json:"r" description:"右边框"`
  157. T LuckySheetDataConfigBorderInfoCell `json:"t" description:"上边框"`
  158. ColIndex int64 `json:"col_index" description:"第几行"`
  159. RowIndex int64 `json:"row_index" description:"第几列"`
  160. }
  161. // LuckySheetDataConfigBorderInfoCell 单元格边框信息(cell类型)
  162. type LuckySheetDataConfigBorderInfoCell struct {
  163. Color string `json:"color" description:"边框颜色 color: 16进制颜色值"`
  164. Style int `description:"边框粗细 style: 1 Thin | 2 Hair | 3 Dotted | 4 Dashed | 5 DashDot | 6 DashDotDot | 7 Double | 8 Medium | 9 MediumDashed | 10 MediumDashDot | 11 MediumDashDotDot | 12 SlantedDashDot | 13 Thick ,和aspose.cells的getLineStyle()的值对应的话,需要自己做个转换,参考 aspose.cells"`
  165. Sl interface{} `json:"style" description:"边框粗细 style: 1 Thin | 2 Hair | 3 Dotted | 4 Dashed | 5 DashDot | 6 DashDotDot | 7 Double | 8 Medium | 9 MediumDashed | 10 MediumDashDot | 11 MediumDashDotDot | 12 SlantedDashDot | 13 Thick ,和aspose.cells的getLineStyle()的值对应的话,需要自己做个转换,参考 aspose.cells"`
  166. }
  167. // LuckySheetCellData 单个单元格数据
  168. type LuckySheetCellData struct {
  169. Col int64 `json:"c" description:"列"`
  170. Row int64 `json:"r" description:"行"`
  171. Value LuckySheetDataValue `json:"v" description:"单元格内值的数据"`
  172. }
  173. // LuckySheetDataValue 单元格内值的数据
  174. type LuckySheetDataValue struct {
  175. CellType LuckySheetDataCellType `json:"ct" description:"单元格值格式:文本、时间等 "`
  176. Value interface{} `json:"v" description:"原始值"`
  177. Monitor string `json:"m" description:"显示值"`
  178. Background string `json:"bg" description:"背景色,实例值:#fff000"`
  179. FontFamily int `description:"字体,0 Times New Roman、 1 Arial、2 Tahoma 、3 Verdana、4 微软雅黑、5 宋体(Song)、6 黑体(ST Heiti)、7 楷体(ST Kaiti)、 8 仿宋(ST FangSong)、9 新宋体(ST Song)、10 华文新魏、11 华文行楷、12 华文隶书 "`
  180. FF interface{} `json:"ff" description:"字体,0 Times New Roman、 1 Arial、2 Tahoma 、3 Verdana、4 微软雅黑、5 宋体(Song)、6 黑体(ST Heiti)、7 楷体(ST Kaiti)、 8 仿宋(ST FangSong)、9 新宋体(ST Song)、10 华文新魏、11 华文行楷、12 华文隶书 "`
  181. FontColor string `json:"fc" description:"字体颜色,示例值:#fff000" `
  182. Bold int `json:"bl" description:"粗体,0 常规 、 1加粗 "`
  183. Italic int `json:"it" description:"斜体,0 常规 、 1 斜体"`
  184. Fontsize int `description:"字体大小,14"`
  185. CancelLine int ` description:"删除线, 0 常规 、 1 删除线"`
  186. HorizontalType int `description:"水平对齐, 0 居中、1 左、2右"`
  187. VerticalType int ` description:"垂直对齐, 0 中间、1 上、2下"`
  188. Fs interface{} `json:"fs" description:"字体大小,14"`
  189. Cl interface{} `json:"cl" description:"删除线, 0 常规 、 1 删除线"`
  190. Ht interface{} `json:"ht" description:"水平对齐, 0 居中、1 左、2右"`
  191. Vt interface{} `json:"vt" description:"垂直对齐, 0 中间、1 上、2下"`
  192. //TextRotate string `json:"tr" description:"竖排文字, 3"`
  193. //RotateText string `json:"rt" description:"文字旋转角度, 介于0~180之间的整数,包含0和180"`
  194. TextBeak int `description:"文本换行, 0 截断、1溢出、2 自动换行"`
  195. Tb interface{} `json:"tb" description:"文本换行, 0 截断、1溢出、2 自动换行"`
  196. Ps LuckySheetDataCellComment `json:"ps" description:"批注"`
  197. Function string `json:"f" description:"公式"`
  198. MergeCell LuckySheetDataConfigMerge `json:"mc" description:"合并单元格信息"`
  199. }
  200. // LuckySheetDataCellType 单元格值格式:文本、时间等
  201. type LuckySheetDataCellType struct {
  202. Fa string `json:"fa" description:"格式名称,例如:“General”为自动格式"`
  203. T string `json:"t" description:"格式类型,例如:“n”为数字类型"`
  204. S []struct {
  205. FontFamily int `description:"字体,0 Times New Roman、 1 Arial、2 Tahoma 、3 Verdana、4 微软雅黑、5 宋体(Song)、6 黑体(ST Heiti)、7 楷体(ST Kaiti)、 8 仿宋(ST FangSong)、9 新宋体(ST Song)、10 华文新魏、11 华文行楷、12 华文隶书 "`
  206. FF interface{} `json:"ff" description:"字体,0 Times New Roman、 1 Arial、2 Tahoma 、3 Verdana、4 微软雅黑、5 宋体(Song)、6 黑体(ST Heiti)、7 楷体(ST Kaiti)、 8 仿宋(ST FangSong)、9 新宋体(ST Song)、10 华文新魏、11 华文行楷、12 华文隶书 "`
  207. FontColor string `json:"fc" description:"字体颜色,示例值:#fff000" `
  208. Fontsize int `description:"字体大小,14"`
  209. CancelLine int ` description:"删除线, 0 常规 、 1 删除线"`
  210. HorizontalType int `description:"水平对齐, 0 居中、1 左、2右"`
  211. VerticalType int `description:"垂直对齐, 0 中间、1 上、2下"`
  212. Fs interface{} `json:"fs" description:"字体大小,14"`
  213. Cl interface{} `json:"cl" description:"删除线, 0 常规 、 1 删除线"`
  214. Ht interface{} `json:"ht" description:"水平对齐, 0 居中、1 左、2右"`
  215. Vt interface{} `json:"vt" description:"垂直对齐, 0 中间、1 上、2下"`
  216. Un int `json:"un" description:""`
  217. Bold int `json:"bl" description:"粗体,0 常规 、 1加粗 "`
  218. Italic int `json:"it" description:"斜体,0 常规 、 1 斜体"`
  219. Value interface{} `json:"v" description:"原始值"`
  220. } `json:"s"`
  221. }
  222. // LuckySheetDataCellComment 批注
  223. type LuckySheetDataCellComment struct {
  224. Left int `json:"left" description:"批注框距离左边工作表边缘位置"`
  225. Top int `json:"top" description:"批注框距离上边工作表边缘位置"`
  226. Width int `json:"width" description:"批注框宽度"`
  227. Height int `json:"height" description:"批注框高度"`
  228. Value string `json:"value" description:"批注内容"`
  229. IsShow bool `json:"isshow" description:"是否显示批注"`
  230. }
  231. // GetLuckySheetData 获取LuckySheetData的结构体
  232. func GetLuckySheetData(jsonStr string) (item *LuckySheetData, err error) {
  233. err = json.Unmarshal([]byte(jsonStr), &item)
  234. for k, v := range item.CellData {
  235. value := v.Value
  236. value.Fontsize = getIntValueByInterface(value.Fs)
  237. value.CancelLine = getIntValueByInterface(value.Cl)
  238. value.HorizontalType = getIntValueByInterface(value.Ht)
  239. value.VerticalType = getIntValueByInterface(value.Vt)
  240. value.FontFamily = getIntValueByInterface(value.FF)
  241. value.TextBeak = getIntValueByInterface(value.Tb)
  242. if len(value.CellType.S) > 0 {
  243. for kk, vv := range value.CellType.S {
  244. vv.Fontsize = getIntValueByInterface(vv.Fs)
  245. vv.CancelLine = getIntValueByInterface(vv.Cl)
  246. vv.HorizontalType = getIntValueByInterface(vv.Ht)
  247. vv.VerticalType = getIntValueByInterface(vv.Vt)
  248. vv.FontFamily = getIntValueByInterface(vv.FF)
  249. value.CellType.S[kk] = vv
  250. }
  251. }
  252. item.CellData[k].Value = value
  253. }
  254. if len(item.Config.BorderInfo) > 0 {
  255. for k, v := range item.Config.BorderInfo {
  256. v.Value.T.Style = getIntValueByInterface(v.Value.T.Style)
  257. v.Value.B.Style = getIntValueByInterface(v.Value.B.Style)
  258. v.Value.L.Style = getIntValueByInterface(v.Value.L.Style)
  259. v.Value.R.Style = getIntValueByInterface(v.Value.R.Style)
  260. item.Config.BorderInfo[k] = v
  261. }
  262. }
  263. return
  264. }
  265. func getIntValueByInterface(valInterface interface{}) (val int) {
  266. if valInterface == nil {
  267. return
  268. }
  269. switch reflect.TypeOf(valInterface).Kind() {
  270. case reflect.String:
  271. tmpValue := reflect.ValueOf(valInterface).String()
  272. tmpValInt, err := strconv.Atoi(tmpValue)
  273. if err != nil {
  274. val = 0
  275. } else {
  276. val = tmpValInt
  277. }
  278. case reflect.Int, reflect.Int32, reflect.Int64:
  279. tmpValue := reflect.ValueOf(valInterface).Int()
  280. val = int(tmpValue)
  281. }
  282. return
  283. }
  284. // TableData 表格数据
  285. type TableData struct {
  286. TableDataList [][]LuckySheetDataValue
  287. RowWidthList []float64
  288. RowHeightList []float64
  289. RemoveTopRow int `description:"移除表格上方的行数"`
  290. RemoveBottomRow int `description:"移除表格下方的行数"`
  291. RemoveLeftColumn int `description:"移除表格左侧的列数"`
  292. RemoveRightColumn int `description:"移除表格右侧的列数"`
  293. MergeList []TableDataMerge `description:"合并数据列"`
  294. }
  295. // TableDataMerge 表格数据合并单元格配置
  296. type TableDataMerge struct {
  297. StartRowIndex int `json:"start_row_index" description:"开始的行下标"`
  298. StartColumnIndex int `json:"start_column" description:"开始的列下标"`
  299. MergeRowNum int `json:"merge_row_num" description:"合并的行数"`
  300. MergeColumnNum int `json:"merge_column_num" description:"合并的列数"`
  301. }
  302. // ToExcel 通过 TableData生成excel表格
  303. func (tableData TableData) ToExcel() (downloadFilePath string, err error) {
  304. //dir, err := os.Executable()
  305. //exPath := filepath.Dir(dir)
  306. //downloadFilePath := exPath + "/" + time.Now().Format(utils.FormatDateTimeUnSpace) + ".xlsx"
  307. downloadFilePath, err = getDownloadPath()
  308. if err != nil {
  309. return
  310. }
  311. xlsxFile := xlsx.NewFile()
  312. if err != nil {
  313. return
  314. }
  315. style := xlsx.NewStyle()
  316. alignment := xlsx.Alignment{
  317. Horizontal: "center",
  318. Vertical: "center",
  319. WrapText: true,
  320. }
  321. style.Alignment = alignment
  322. style.ApplyAlignment = true
  323. sheet, err := xlsxFile.AddSheet("sheet1")
  324. if err != nil {
  325. return
  326. }
  327. for k, v := range tableData.RowWidthList {
  328. err = sheet.SetColWidth(k, k, v/10)
  329. if err != nil {
  330. return
  331. }
  332. }
  333. // 单元格高度配置列表
  334. lenRowHeight := len(tableData.RowHeightList)
  335. for index, v := range tableData.TableDataList {
  336. tmpRow := sheet.AddRow()
  337. //设置单元格高度
  338. if index < lenRowHeight && tableData.RowHeightList[index] > 0 {
  339. tmpRow.SetHeight(tableData.RowHeightList[index] / 2)
  340. }
  341. for _, cellInfo := range v {
  342. tmpStyle := new(xlsx.Style)
  343. //xlsx.Style{
  344. // Fill: xlsx.Fill{},
  345. // ApplyBorder: false,
  346. // ApplyFill: false,
  347. // ApplyFont: false,
  348. // NamedStyleIndex: nil,
  349. //}
  350. //fill := *NewFill("solid", "FF000000", "00FF0000")
  351. defaultFill := xlsx.DefaultFill()
  352. if cellInfo.Background != `` {
  353. defaultFill.PatternType = "solid"
  354. backgroundColor := cellInfo.Background
  355. // 这么做是为了避免传入的是RGB的格式(rgb(255, 255, 255))
  356. backgroundColor = getColor(backgroundColor)
  357. defaultFill.BgColor = strings.TrimPrefix(backgroundColor, "#")
  358. defaultFill.FgColor = strings.TrimPrefix(backgroundColor, "#")
  359. }
  360. tmpStyle.Fill = *defaultFill
  361. // 获取表格字体配置
  362. tmpStyle.Font = getExcelFontConf(cellInfo)
  363. //获取表格单元格排列配置
  364. tmpStyle.ApplyAlignment = true
  365. tmpStyle.Alignment = getExcelAlignmentConf(cellInfo)
  366. //边框配置
  367. tmpStyle.Border = xlsx.Border{
  368. Left: "thin",
  369. LeftColor: "000000",
  370. Right: "thin",
  371. RightColor: "000000",
  372. Top: "thin",
  373. TopColor: "000000",
  374. Bottom: "thin",
  375. BottomColor: "000000",
  376. }
  377. //tmpStyle.ApplyAlignment = true
  378. //tmpStyle.Alignment.WrapText = true
  379. tmpRow := tmpRow.AddCell()
  380. tmpRow.SetStyle(tmpStyle)
  381. valueStr := cellInfo.Monitor
  382. if valueStr == `` {
  383. //valueStr = fmt.Sprint(cellInfo.Value)
  384. if valueStr == `` && cellInfo.CellType.S != nil {
  385. //不是设置在单元格上面,而是设置在文本上
  386. for _, cellS := range cellInfo.CellType.S {
  387. valueStr += fmt.Sprint(cellS.Value)
  388. }
  389. }
  390. }
  391. tmpRow.SetString(valueStr)
  392. //if cellInfo.Function != `` {
  393. // tmpRow.SetFormula(cellInfo.Function)
  394. //}
  395. }
  396. }
  397. for _, v := range tableData.MergeList {
  398. for k, cell := range sheet.Row(v.StartRowIndex).Cells {
  399. if v.StartColumnIndex == k {
  400. cell.Merge(v.MergeColumnNum, v.MergeRowNum)
  401. }
  402. }
  403. }
  404. //return
  405. err = xlsxFile.Save(downloadFilePath)
  406. if err != nil {
  407. return
  408. }
  409. //randStr := time.Now().Format(utils.FormatDateTimeUnSpace)
  410. //downloadFileName := "即将到期客户数据_" + randStr + ".xlsx"
  411. //this.Ctx.Output.Download(downLoadnFilePath, downloadFileName)
  412. return
  413. }
  414. // GetTableDataByLuckySheetDataStr 通过LuckySheet的string数据获取表格数据
  415. func (item *LuckySheetData) GetTableDataByLuckySheetDataStr() (selfTableData TableData, err error) {
  416. luckySheetCellDataList := item.CellData
  417. // 表格数据
  418. tableDataMap := make(map[int64]map[int64]LuckySheetDataValue)
  419. // 最大行,最大列
  420. var maxRow, maxCol int64
  421. for _, v := range luckySheetCellDataList {
  422. //fmt.Println("row:", v.Row, "=====col:", v.Col)
  423. if v.Row > maxRow { //最大行
  424. maxRow = v.Row
  425. }
  426. if v.Col > maxCol { //最大列
  427. maxCol = v.Col
  428. }
  429. var tmpRow map[int64]LuckySheetDataValue
  430. tmpRow, ok := tableDataMap[v.Row]
  431. if ok {
  432. tmpRow[v.Col] = v.Value
  433. } else {
  434. tmpRow = make(map[int64]LuckySheetDataValue)
  435. tmpRow[v.Col] = v.Value
  436. }
  437. tableDataMap[v.Row] = tmpRow
  438. }
  439. tableDataList := make([][]LuckySheetDataValue, 0)
  440. var i int64
  441. // 单元格宽度
  442. configColumnConf := item.Config.Columnlen
  443. rowWidthMap := make(map[int]float64)
  444. rowWidthList := make([]float64, 0) //
  445. // 单元格高度
  446. configRowConf := item.Config.Rowlen
  447. rowHeightList := make([]float64, 0) //
  448. for i = 0; i <= maxRow; i++ {
  449. //列
  450. tmpTableColDataList := make([]LuckySheetDataValue, 0)
  451. // 每个单元格的高度
  452. tmpHeight, ok := configRowConf[fmt.Sprint(i)]
  453. if !ok {
  454. tmpHeight = 0
  455. }
  456. rowHeightList = append(rowHeightList, tmpHeight)
  457. tmpRowData, ok := tableDataMap[i]
  458. // 如果没有该行数据,那么就默认添加空行数据处理
  459. if !ok {
  460. tmpRowData = make(map[int64]LuckySheetDataValue)
  461. }
  462. var j int64
  463. for j = 0; j <= maxCol; j++ {
  464. tmpTableColData, ok := tmpRowData[j]
  465. if !ok {
  466. tmpTableColData = LuckySheetDataValue{}
  467. }
  468. //单元格显示的数据处理
  469. tmpTableColData.Monitor = handleCellVal(tmpTableColData)
  470. tmpTableColDataList = append(tmpTableColDataList, tmpTableColData)
  471. // 每个单元格的宽度
  472. tmpWidth, ok := configColumnConf[fmt.Sprint(j)]
  473. if !ok {
  474. tmpWidth = 0
  475. }
  476. rowIndex := len(tmpTableColDataList) - 1
  477. if _, ok2 := rowWidthMap[rowIndex]; !ok2 {
  478. rowWidthList = append(rowWidthList, tmpWidth)
  479. }
  480. rowWidthMap[rowIndex] = tmpWidth
  481. }
  482. tableDataList = append(tableDataList, tmpTableColDataList)
  483. }
  484. // 数据处理,移除上下左右空行空列
  485. tableDataList, tableRemoveNum, rowHeightList, rowWidthList, tableDataMergeList := handleTableDataList(tableDataList, item.Config.Merge, rowHeightList, rowWidthList)
  486. // 表格数据
  487. {
  488. // 移除空白单元格信息
  489. selfTableData.RemoveTopRow = tableRemoveNum.RemoveTopRow
  490. selfTableData.RemoveBottomRow = tableRemoveNum.RemoveBottomRow
  491. selfTableData.RemoveLeftColumn = tableRemoveNum.RemoveLeftColumn
  492. selfTableData.RemoveRightColumn = tableRemoveNum.RemoveRightColumn
  493. }
  494. selfTableData.TableDataList = tableDataList
  495. selfTableData.RowWidthList = rowWidthList
  496. selfTableData.RowHeightList = rowHeightList
  497. selfTableData.MergeList = tableDataMergeList
  498. return
  499. }
  500. // TableRemoveNum 上下左右移除的空行空列数量
  501. type TableRemoveNum struct {
  502. RemoveTopRow int `description:"移除表格上方的行数"`
  503. RemoveBottomRow int `description:"移除表格下方的行数"`
  504. RemoveLeftColumn int `description:"移除表格左侧的列数"`
  505. RemoveRightColumn int `description:"移除表格右侧的列数"`
  506. }
  507. // handleTableDataList 表格数据处理(移除上下左右的空行空列)
  508. func handleTableDataList(tableDataList [][]LuckySheetDataValue, luckySheetDataConfigMergeList map[string]LuckySheetDataConfigMerge, rowHeightList, rowWidthList []float64) ([][]LuckySheetDataValue, TableRemoveNum, []float64, []float64, []TableDataMerge) {
  509. var removeTopRow, removeBottomRow, removeLeftColumn, removeRightColumn int //上下左右需要移除的空行空列
  510. tableDataMergeList := make([]TableDataMerge, 0) //待合并的单元格信息
  511. //总共多少行
  512. lenRow := len(tableDataList)
  513. //移除上下空行
  514. deleteRowIndexList := make([]int, 0)
  515. if lenRow > 0 {
  516. var flag = false
  517. // 移除上方空列
  518. for rowIndex := 0; rowIndex < lenRow; rowIndex++ {
  519. isDelete := true
  520. for _, v := range tableDataList[rowIndex] {
  521. if v.Monitor != `` || (v.MergeCell.Row != rowIndex && v.MergeCell.Row != 0) {
  522. isDelete = false
  523. flag = true
  524. break
  525. }
  526. }
  527. if flag {
  528. break
  529. }
  530. if isDelete {
  531. removeTopRow++
  532. deleteRowIndexList = append(deleteRowIndexList, rowIndex)
  533. }
  534. }
  535. // 移除下方空行
  536. flag = false
  537. //尾部
  538. deleteBottomRowIndexList := make([]int, 0)
  539. for rowIndex := lenRow - 1; rowIndex >= 0; rowIndex-- {
  540. isDelete := true
  541. for _, v := range tableDataList[rowIndex] {
  542. if v.Monitor != `` {
  543. isDelete = false
  544. flag = true
  545. break
  546. }
  547. }
  548. if flag {
  549. break
  550. }
  551. if isDelete {
  552. deleteBottomRowIndexList = append(deleteBottomRowIndexList, rowIndex)
  553. removeBottomRow++
  554. }
  555. }
  556. if len(deleteBottomRowIndexList) > 0 {
  557. deleteRowIndexList = append(deleteRowIndexList, utils.RevSlice(deleteBottomRowIndexList)...)
  558. }
  559. lenDeleteRow := len(deleteRowIndexList)
  560. if lenDeleteRow > 0 {
  561. for rowIndex := lenDeleteRow - 1; rowIndex >= 0; rowIndex-- {
  562. //表格数据
  563. tableDataList = append(tableDataList[:deleteRowIndexList[rowIndex]], tableDataList[deleteRowIndexList[rowIndex]+1:]...) // 删除开头N个元素
  564. //表格高度
  565. rowHeightList = append(rowHeightList[:deleteRowIndexList[rowIndex]], rowHeightList[deleteRowIndexList[rowIndex]+1:]...) // 删除开头N个元素
  566. }
  567. }
  568. }
  569. //移除左右空列
  570. deleteColumnIndexList := make([]int, 0)
  571. if len(tableDataList) > 0 {
  572. var flag = false
  573. lenColumn := len(tableDataList[0])
  574. // 移除左边空列
  575. for columnIndex := 0; columnIndex < lenColumn; columnIndex++ {
  576. isDelete := true
  577. for _, v := range tableDataList {
  578. //如果一列都没有,说明是上面几行是空行,没有数据
  579. if len(v) <= 0 {
  580. continue
  581. }
  582. if v[columnIndex].Monitor != `` || (v[columnIndex].MergeCell.Column != columnIndex && v[columnIndex].MergeCell.Column != 0) {
  583. isDelete = false
  584. flag = true
  585. break
  586. }
  587. }
  588. if flag {
  589. break
  590. }
  591. if isDelete {
  592. removeLeftColumn++
  593. deleteColumnIndexList = append(deleteColumnIndexList, columnIndex)
  594. }
  595. }
  596. // 移除右方空列
  597. flag = false
  598. //右边
  599. deleteTailColumnIndexList := make([]int, 0)
  600. for columnIndex := lenColumn - 1; columnIndex >= 0; columnIndex-- {
  601. isDelete := true
  602. for _, v := range tableDataList {
  603. //如果一列都没有,说明是上面几行是空行,没有数据
  604. if len(v) <= 0 {
  605. continue
  606. }
  607. if v[columnIndex].Monitor != `` || (v[columnIndex].MergeCell.Column != columnIndex && v[columnIndex].MergeCell.Column != 0) {
  608. isDelete = false
  609. flag = true
  610. break
  611. }
  612. }
  613. if flag {
  614. break
  615. }
  616. if isDelete {
  617. deleteTailColumnIndexList = append(deleteTailColumnIndexList, columnIndex)
  618. removeRightColumn++
  619. }
  620. }
  621. if len(deleteTailColumnIndexList) > 0 {
  622. deleteColumnIndexList = append(deleteColumnIndexList, utils.RevSlice(deleteTailColumnIndexList)...)
  623. }
  624. lenDeleteColumn := len(deleteColumnIndexList)
  625. if lenDeleteColumn > 0 {
  626. for columnIndex := lenDeleteColumn - 1; columnIndex >= 0; columnIndex-- {
  627. //表格数据
  628. for k, v := range tableDataList {
  629. tableDataList[k] = append(v[:deleteColumnIndexList[columnIndex]], v[deleteColumnIndexList[columnIndex]+1:]...) // 删除开头N个元素
  630. }
  631. //表格宽度
  632. rowWidthList = append(rowWidthList[:deleteColumnIndexList[columnIndex]], rowWidthList[deleteColumnIndexList[columnIndex]+1:]...) // 删除开头N个元素
  633. }
  634. }
  635. }
  636. //处理合并单元格
  637. for _, v := range luckySheetDataConfigMergeList {
  638. indexRow := v.Row - removeTopRow
  639. indexColumn := v.Column - removeLeftColumn
  640. tableDataMerge := TableDataMerge{
  641. StartRowIndex: indexRow,
  642. StartColumnIndex: indexColumn,
  643. MergeRowNum: v.Rs - 1,
  644. MergeColumnNum: v.Cs - 1,
  645. }
  646. tableDataMergeList = append(tableDataMergeList, tableDataMerge)
  647. }
  648. return tableDataList, TableRemoveNum{
  649. RemoveTopRow: removeTopRow,
  650. RemoveBottomRow: removeBottomRow,
  651. RemoveLeftColumn: removeLeftColumn,
  652. RemoveRightColumn: removeRightColumn,
  653. }, rowHeightList, rowWidthList, tableDataMergeList
  654. }
  655. // ToExcel 通过 luckySheetData生成excel表格
  656. func (item *LuckySheetData) ToExcel() (downloadFilePath string, err error) {
  657. tableData, err := item.GetTableDataByLuckySheetDataStr()
  658. if err != nil {
  659. return
  660. }
  661. downloadFilePath, err = tableData.ToExcel()
  662. return
  663. }
  664. // getDownloadPath 获取下载地址
  665. func getDownloadPath() (fpath string, err error) {
  666. dateDir := time.Now().Format("20060102")
  667. uploadDir := "static/xls/" + dateDir
  668. err = os.MkdirAll(uploadDir, 0766)
  669. if err != nil {
  670. return
  671. }
  672. randStr := utils.GetRandStringNoSpecialChar(28)
  673. fileName := randStr + ".xlsx"
  674. fpath = uploadDir + "/" + fileName
  675. return
  676. }
  677. // getExcelFontConf 获取表格字体配置
  678. func getExcelFontConf(cellInfo LuckySheetDataValue) xlsx.Font {
  679. fontSize := 10
  680. familyName := ``
  681. var isBold, isItalic, isUnderline bool
  682. // 字体
  683. {
  684. if cellInfo.Bold == 1 {
  685. isBold = true
  686. }
  687. if cellInfo.Italic == 1 {
  688. isItalic = true
  689. }
  690. if cellInfo.CancelLine == 1 {
  691. isUnderline = true
  692. }
  693. //if cellInfo.Fontsize != `` {
  694. // convSize, _ := strconv.Atoi(cellInfo.Fontsize)
  695. // if convSize > 0 {
  696. // fontSize = convSize
  697. // }
  698. //}
  699. if cellInfo.Fontsize > 0 {
  700. fontSize = cellInfo.Fontsize
  701. }
  702. tmpFamilyName, familyNameOk := LuckyFontFamilyMap[cellInfo.FontFamily]
  703. if !familyNameOk {
  704. tmpFamilyName = "宋体"
  705. }
  706. familyName = tmpFamilyName
  707. }
  708. return xlsx.Font{
  709. Size: fontSize,
  710. Name: familyName,
  711. //Family: v2.FontFamily,
  712. //Charset: 0,
  713. Color: strings.TrimPrefix(cellInfo.FontColor, "#"),
  714. Bold: isBold,
  715. Italic: isItalic,
  716. Underline: isUnderline,
  717. }
  718. }
  719. // getExcelAlignmentConf 获取表格单元格排列配置
  720. func getExcelAlignmentConf(cellInfo LuckySheetDataValue) xlsx.Alignment {
  721. //自动换行
  722. isWrapText := false
  723. if cellInfo.TextBeak == 2 {
  724. isWrapText = true
  725. }
  726. rotateText := 0
  727. //if cellInfo.RotateText != `` {
  728. // convSize, _ := strconv.Atoi(cellInfo.RotateText)
  729. // if convSize > 0 {
  730. // rotateText = convSize
  731. // }
  732. //}
  733. return xlsx.Alignment{
  734. Horizontal: LuckyHorizontalMap[cellInfo.HorizontalType],
  735. //Indent: 0,
  736. //ShrinkToFit: false,
  737. TextRotation: rotateText,
  738. Vertical: LuckyVerticalMap[cellInfo.VerticalType],
  739. WrapText: isWrapText,
  740. }
  741. }
  742. // getExcelBorderConf 获取表格边框配置
  743. //func getExcelBorderConf(list []LuckySheetDataConfigBorderInfo) (v xlsx.Border) {
  744. // // 字体
  745. // for _, v := range list {
  746. // //v.BorderType
  747. // //v.Style
  748. //
  749. // if v.RangeType == "cell" {
  750. //
  751. // xlsx.Border{
  752. // Left: LuckyBorderMap[v.Value.L.Style],
  753. // LeftColor: strings.TrimPrefix(v.Value.L.Color, "#"),
  754. // Right: LuckyBorderMap[v.Value.R.Style],
  755. // RightColor: strings.TrimPrefix(v.Value.R.Color, "#"),
  756. // Top: LuckyBorderMap[v.Value.T.Style],
  757. // TopColor: strings.TrimPrefix(v.Value.T.Color, "#"),
  758. // Bottom: LuckyBorderMap[v.Value.B.Style],
  759. // BottomColor: strings.TrimPrefix(v.Value.B.Color, "#"),
  760. // }
  761. // } else {
  762. // xlsx.Border{
  763. // Left: LuckyBorderMap[v.Style],
  764. // LeftColor: strings.TrimPrefix(v.Color, "#"),
  765. // Right: LuckyBorderMap[v.Style],
  766. // RightColor: strings.TrimPrefix(v.Color, "#"),
  767. // Top: LuckyBorderMap[v.Style],
  768. // TopColor: strings.TrimPrefix(v.Color, "#"),
  769. // Bottom: LuckyBorderMap[v.Style],
  770. // BottomColor: strings.TrimPrefix(v.Color, "#"),
  771. // }
  772. // }
  773. // //v.Value.T.Style
  774. //
  775. // }
  776. //
  777. // return
  778. //}
  779. // LuckyFontFamilyMap 字体map
  780. var LuckyFontFamilyMap = map[int]string{
  781. 0: "Times New Roman",
  782. 1: "Arial",
  783. 2: "Tahoma",
  784. 3: "Verdana",
  785. 4: "微软雅黑",
  786. 5: "宋体", //宋体(Song)、
  787. 6: "黑体", // 黑体(ST Heiti)
  788. 7: "楷体", //楷体(ST Kaiti),
  789. 8: "仿宋", //仿宋(ST FangSong),
  790. 9: "新宋体", //新宋体(ST Song),
  791. 10: "华文新魏",
  792. 11: "华文行楷",
  793. 12: "华文隶书",
  794. }
  795. // LuckyBorderMap 边框map
  796. var LuckyBorderMap = map[string]string{
  797. "": "Thin",
  798. "1": "Thin",
  799. "2": "Hair",
  800. "3": "Dotted",
  801. "4": "Dashed",
  802. "5": "DashDot", //宋体(Song)、
  803. "6": "DashDotDot", // 黑体(ST Heiti)
  804. "7": "Double", //楷体(ST Kaiti),
  805. "8": "Medium", //仿宋(ST FangSong),
  806. "9": "MediumDashed", //新宋体(ST Song),
  807. "10": "MediumDashDot",
  808. "11": "MediumDashDotDot",
  809. "12": "SlantedDashDot",
  810. "13": "Thick",
  811. }
  812. // LuckyHorizontalMap 水平对齐map
  813. var LuckyHorizontalMap = map[int]string{
  814. //"": "general",
  815. 0: "center",
  816. 1: "left",
  817. 2: "right",
  818. }
  819. // LuckyVerticalMap 垂直对齐map
  820. var LuckyVerticalMap = map[int]string{
  821. //"": "center",
  822. 0: "center",
  823. 1: "top",
  824. //2: "bottom",
  825. }
  826. // GetColumnName Return the ColumnName
  827. func GetColumnName(rowNumber int, colNumber int) (colName string, err error) {
  828. if rowNumber < 1 || colNumber < 1 {
  829. err = errors.New("Row and Column Number can not be less than 1")
  830. return
  831. }
  832. dividend := colNumber
  833. var modulo int
  834. for dividend > 0 {
  835. modulo = (dividend - 1) % 26
  836. // Convert int to char
  837. colName = string(65+modulo) + colName
  838. dividend = (int)((dividend - modulo) / 26)
  839. }
  840. colName = colName + strconv.Itoa(rowNumber)
  841. return
  842. }
  843. // GetTableDataByLuckySheetDataStrBak 通过LuckySheet的string数据获取表格数据(备份:2022-08-23 10:30:32)
  844. func (item *LuckySheetData) GetTableDataByLuckySheetDataStrBak() (selfTableData TableData, err error) {
  845. luckySheetCellDataList := item.CellData
  846. // 表格数据
  847. tableDataMap := make(map[int64]map[int64]LuckySheetDataValue)
  848. // 最大行,最大列
  849. var maxRow, maxCol int64
  850. for _, v := range luckySheetCellDataList {
  851. //fmt.Println("row:", v.Row, "=====col:", v.Col)
  852. if v.Row > maxRow { //最大行
  853. maxRow = v.Row
  854. }
  855. if v.Col > maxCol { //最大列
  856. maxCol = v.Col
  857. }
  858. var tmpRow map[int64]LuckySheetDataValue
  859. tmpRow, ok := tableDataMap[v.Row]
  860. if ok {
  861. tmpRow[v.Col] = v.Value
  862. } else {
  863. tmpRow = make(map[int64]LuckySheetDataValue)
  864. tmpRow[v.Col] = v.Value
  865. }
  866. tableDataMap[v.Row] = tmpRow
  867. }
  868. tableDataList := make([][]LuckySheetDataValue, 0)
  869. var i int64
  870. // 单元格宽度
  871. configColumnConf := item.Config.Columnlen
  872. rowWidthMap := make(map[int]float64)
  873. rowWidthList := make([]float64, 0) //
  874. // 单元格高度
  875. configRowConf := item.Config.Rowlen
  876. rowHeightList := make([]float64, 0) //
  877. for i = 0; i <= maxRow; i++ {
  878. //列
  879. tmpTableColDataList := make([]LuckySheetDataValue, 0)
  880. // 每个单元格的高度
  881. tmpHeight, ok := configRowConf[fmt.Sprint(i)]
  882. if !ok {
  883. tmpHeight = 0
  884. }
  885. rowHeightList = append(rowHeightList, tmpHeight)
  886. tmpRowData, ok := tableDataMap[i]
  887. // 如果没有该行数据,那么就默认添加空行数据处理
  888. if !ok {
  889. tmpRowData = make(map[int64]LuckySheetDataValue)
  890. }
  891. var j int64
  892. for j = 0; j <= maxCol; j++ {
  893. tmpTableColData, ok := tmpRowData[j]
  894. if !ok {
  895. tmpTableColData = LuckySheetDataValue{}
  896. }
  897. tmpTableColDataList = append(tmpTableColDataList, tmpTableColData)
  898. // 每个单元格的宽度
  899. tmpWidth, ok := configColumnConf[fmt.Sprint(j)]
  900. if !ok {
  901. tmpWidth = 0
  902. }
  903. rowIndex := len(tmpTableColDataList) - 1
  904. if _, ok2 := rowWidthMap[rowIndex]; !ok2 {
  905. rowWidthList = append(rowWidthList, tmpWidth)
  906. }
  907. rowWidthMap[rowIndex] = tmpWidth
  908. }
  909. tableDataList = append(tableDataList, tmpTableColDataList)
  910. }
  911. //总共多少行
  912. lenRow := len(tableDataList)
  913. //移除上下空行
  914. deleteRowIndexList := make([]int, 0)
  915. if lenRow > 0 {
  916. var flag = false
  917. // 移除上方空列
  918. for rowIndex := 0; rowIndex < lenRow; rowIndex++ {
  919. isDelete := true
  920. for _, v := range tableDataList[rowIndex] {
  921. if v.Monitor != `` || (v.MergeCell.Row != rowIndex && v.MergeCell.Row != 0) {
  922. isDelete = false
  923. flag = true
  924. break
  925. }
  926. }
  927. if flag {
  928. break
  929. }
  930. if isDelete {
  931. selfTableData.RemoveTopRow++
  932. deleteRowIndexList = append(deleteRowIndexList, rowIndex)
  933. }
  934. }
  935. // 移除下方空行
  936. flag = false
  937. //尾部
  938. deleteBottomRowIndexList := make([]int, 0)
  939. for rowIndex := lenRow - 1; rowIndex >= 0; rowIndex-- {
  940. isDelete := true
  941. for _, v := range tableDataList[rowIndex] {
  942. if v.Monitor != `` {
  943. isDelete = false
  944. flag = true
  945. break
  946. }
  947. }
  948. if flag {
  949. break
  950. }
  951. if isDelete {
  952. deleteBottomRowIndexList = append(deleteBottomRowIndexList, rowIndex)
  953. selfTableData.RemoveBottomRow++
  954. }
  955. }
  956. if len(deleteBottomRowIndexList) > 0 {
  957. deleteRowIndexList = append(deleteRowIndexList, utils.RevSlice(deleteBottomRowIndexList)...)
  958. }
  959. lenDeleteRow := len(deleteRowIndexList)
  960. if lenDeleteRow > 0 {
  961. for rowIndex := lenDeleteRow - 1; rowIndex >= 0; rowIndex-- {
  962. //表格数据
  963. tableDataList = append(tableDataList[:deleteRowIndexList[rowIndex]], tableDataList[deleteRowIndexList[rowIndex]+1:]...) // 删除开头N个元素
  964. //表格高度
  965. rowHeightList = append(rowHeightList[:deleteRowIndexList[rowIndex]], rowHeightList[deleteRowIndexList[rowIndex]+1:]...) // 删除开头N个元素
  966. }
  967. }
  968. }
  969. //移除左右空列
  970. deleteColumnIndexList := make([]int, 0)
  971. if len(tableDataList) > 0 {
  972. var flag = false
  973. lenColumn := len(tableDataList[0])
  974. // 移除左边空列
  975. for columnIndex := 0; columnIndex < lenColumn; columnIndex++ {
  976. isDelete := true
  977. for _, v := range tableDataList {
  978. //如果一列都没有,说明是上面几行是空行,没有数据
  979. if len(v) <= 0 {
  980. continue
  981. }
  982. if v[columnIndex].Monitor != `` || (v[columnIndex].MergeCell.Column != columnIndex && v[columnIndex].MergeCell.Column != 0) {
  983. isDelete = false
  984. flag = true
  985. break
  986. }
  987. }
  988. if flag {
  989. break
  990. }
  991. if isDelete {
  992. selfTableData.RemoveLeftColumn++
  993. deleteColumnIndexList = append(deleteColumnIndexList, columnIndex)
  994. }
  995. }
  996. // 移除右方空列
  997. flag = false
  998. //右边
  999. deleteTailColumnIndexList := make([]int, 0)
  1000. for columnIndex := lenColumn - 1; columnIndex >= 0; columnIndex-- {
  1001. isDelete := true
  1002. for _, v := range tableDataList {
  1003. //如果一列都没有,说明是上面几行是空行,没有数据
  1004. if len(v) <= 0 {
  1005. continue
  1006. }
  1007. if v[columnIndex].Monitor != `` || (v[columnIndex].MergeCell.Column != columnIndex && v[columnIndex].MergeCell.Column != 0) {
  1008. isDelete = false
  1009. flag = true
  1010. break
  1011. }
  1012. }
  1013. if flag {
  1014. break
  1015. }
  1016. if isDelete {
  1017. deleteTailColumnIndexList = append(deleteTailColumnIndexList, columnIndex)
  1018. selfTableData.RemoveRightColumn++
  1019. }
  1020. }
  1021. if len(deleteTailColumnIndexList) > 0 {
  1022. deleteColumnIndexList = append(deleteColumnIndexList, utils.RevSlice(deleteTailColumnIndexList)...)
  1023. }
  1024. lenDeleteColumn := len(deleteColumnIndexList)
  1025. if lenDeleteColumn > 0 {
  1026. for columnIndex := lenDeleteColumn - 1; columnIndex >= 0; columnIndex-- {
  1027. //表格数据
  1028. for k, v := range tableDataList {
  1029. tableDataList[k] = append(v[:deleteColumnIndexList[columnIndex]], v[deleteColumnIndexList[columnIndex]+1:]...) // 删除开头N个元素
  1030. }
  1031. //表格宽度
  1032. rowWidthList = append(rowWidthList[:deleteColumnIndexList[columnIndex]], rowWidthList[deleteColumnIndexList[columnIndex]+1:]...) // 删除开头N个元素
  1033. }
  1034. }
  1035. }
  1036. //处理合并单元格
  1037. tableDataMergeList := make([]TableDataMerge, 0)
  1038. for _, v := range item.Config.Merge {
  1039. indexRow := v.Row - selfTableData.RemoveTopRow
  1040. indexColumn := v.Column - selfTableData.RemoveLeftColumn
  1041. tableDataMerge := TableDataMerge{
  1042. StartRowIndex: indexRow,
  1043. StartColumnIndex: indexColumn,
  1044. MergeRowNum: v.Rs - 1,
  1045. MergeColumnNum: v.Cs - 1,
  1046. }
  1047. tableDataMergeList = append(tableDataMergeList, tableDataMerge)
  1048. }
  1049. // 表格数据
  1050. selfTableData.TableDataList = tableDataList
  1051. selfTableData.RowWidthList = rowWidthList
  1052. selfTableData.RowHeightList = rowHeightList
  1053. selfTableData.MergeList = tableDataMergeList
  1054. return
  1055. }
  1056. func (item *LuckySheetData) ToExcel2() (downloadFilePath string, err error) {
  1057. tableData, err := item.GetTableDataByLuckySheetDataStr()
  1058. downloadFilePath, err = getDownloadPath()
  1059. if err != nil {
  1060. return
  1061. }
  1062. f := excelize.NewFile()
  1063. // Create a new sheet.
  1064. sheetName := `Sheet1`
  1065. sheetIndex := f.NewSheet(sheetName)
  1066. //设置列宽度
  1067. for k, v := range tableData.RowWidthList {
  1068. colName, tmpErr := excelize.ColumnNumberToName(k + 1)
  1069. if tmpErr != nil {
  1070. err = errors.New("获取单元格列名失败,ERR:" + tmpErr.Error())
  1071. err = tmpErr
  1072. return
  1073. }
  1074. err = f.SetColWidth(sheetName, colName, colName, v/10)
  1075. if err != nil {
  1076. err = errors.New("设置列宽度,ERR:" + tmpErr.Error())
  1077. return
  1078. }
  1079. }
  1080. // 写入数据
  1081. for index, v := range tableData.TableDataList {
  1082. //设置单元格高度
  1083. if tableData.RowHeightList[index] > 0 {
  1084. tmpErr := f.SetRowHeight(sheetName, index+1, tableData.RowHeightList[index]/2)
  1085. if tmpErr != nil {
  1086. err = errors.New("设置单元格高度失败,ERR:" + tmpErr.Error())
  1087. return
  1088. }
  1089. }
  1090. for colunmIndex, cellInfo := range v {
  1091. //f.NewStyle
  1092. defaultFill := excelize.Fill{
  1093. //Type: "solid",
  1094. Pattern: 1,
  1095. //Color: []string{cellInfo.Background},
  1096. Shading: 0,
  1097. }
  1098. if cellInfo.Background != `` {
  1099. defaultFill.Type = "solid"
  1100. defaultFill.Color = []string{cellInfo.Background}
  1101. }
  1102. cellStyle := &excelize.Style{
  1103. Border: []excelize.Border{
  1104. {Type: "left", Color: "000000", Style: 1},
  1105. {Type: "top", Color: "000000", Style: 1},
  1106. {Type: "bottom", Color: "000000", Style: 1},
  1107. {Type: "right", Color: "000000", Style: 1},
  1108. //{Type: "diagonalDown", Color: "A020F0", Style: 7},
  1109. //{Type: "diagonalUp", Color: "A020F0", Style: 8},
  1110. },
  1111. Fill: defaultFill,
  1112. Font: getExcelizeFontConf(cellInfo),
  1113. Alignment: getExcelizeAlignmentConf(cellInfo),
  1114. //Protection: nil,
  1115. //NumFmt: 0,
  1116. //DecimalPlaces: 0,
  1117. //CustomNumFmt: nil,
  1118. //Lang: "",
  1119. //NegRed: false,
  1120. }
  1121. cellStyleId, tmpErr := f.NewStyle(cellStyle)
  1122. if tmpErr != nil {
  1123. err = errors.New("new Style 失败,ERR:" + tmpErr.Error())
  1124. return
  1125. }
  1126. columnName, tmpErr := excelize.ColumnNumberToName(colunmIndex + 1)
  1127. if tmpErr != nil {
  1128. err = errors.New("获取单元格列名失败,ERR:" + tmpErr.Error())
  1129. return
  1130. }
  1131. cellName := columnName + strconv.Itoa(index+1)
  1132. tmpErr = f.SetCellStyle(sheetName, cellName, cellName, cellStyleId)
  1133. if tmpErr != nil {
  1134. err = errors.New("设置style失败,ERR:" + tmpErr.Error())
  1135. return
  1136. }
  1137. valueStr := cellInfo.Monitor
  1138. if valueStr == `` {
  1139. //valueStr = fmt.Sprint(cellInfo.Value)
  1140. if valueStr == `` && cellInfo.CellType.S != nil {
  1141. //不是设置在单元格上面,而是设置在文本上
  1142. for _, cellS := range cellInfo.CellType.S {
  1143. valueStr += fmt.Sprint(cellS.Value)
  1144. }
  1145. }
  1146. }
  1147. tmpErr = f.SetCellStr(sheetName, cellName, valueStr)
  1148. if tmpErr != nil {
  1149. err = errors.New("设置单元格数据失败,ERR:" + tmpErr.Error())
  1150. return
  1151. }
  1152. }
  1153. }
  1154. for _, v := range tableData.MergeList {
  1155. //开始列
  1156. startColumnName, tmpErr := excelize.ColumnNumberToName(v.StartColumnIndex + 1)
  1157. if tmpErr != nil {
  1158. err = tmpErr
  1159. return
  1160. }
  1161. startCellName := startColumnName + strconv.Itoa(v.StartRowIndex+1)
  1162. //结束列
  1163. endColumnName, tmpErr := excelize.ColumnNumberToName(v.StartColumnIndex + v.MergeColumnNum + 1)
  1164. if tmpErr != nil {
  1165. err = tmpErr
  1166. return
  1167. }
  1168. endCellName := endColumnName + strconv.Itoa(v.StartRowIndex+v.MergeRowNum+1)
  1169. err = f.MergeCell(sheetName, startCellName, endCellName)
  1170. if err != nil {
  1171. return
  1172. }
  1173. }
  1174. // Set active sheet of the workbook.
  1175. f.SetActiveSheet(sheetIndex)
  1176. // Save spreadsheet by the given path.
  1177. err = f.SaveAs(downloadFilePath)
  1178. return
  1179. }
  1180. // getExcelizeFontConf 获取表格字体配置
  1181. func getExcelizeFontConf(cellInfo LuckySheetDataValue) *excelize.Font {
  1182. fontSize := 10
  1183. familyName := ``
  1184. //single 单线 、double 双线
  1185. underlineStyle := ``
  1186. var isBold, isItalic, isUnderline bool
  1187. // 字体
  1188. {
  1189. if cellInfo.Bold == 1 {
  1190. isBold = true
  1191. }
  1192. if cellInfo.Italic == 1 {
  1193. isItalic = true
  1194. }
  1195. if cellInfo.CancelLine == 1 {
  1196. isUnderline = true
  1197. }
  1198. //if cellInfo.Fontsize != `` {
  1199. // convSize, _ := strconv.Atoi(cellInfo.Fontsize)
  1200. // if convSize > 0 {
  1201. // fontSize = convSize
  1202. // }
  1203. //}
  1204. if cellInfo.Fontsize > 0 {
  1205. fontSize = cellInfo.Fontsize
  1206. }
  1207. tmpFamilyName, familyNameOk := LuckyFontFamilyMap[cellInfo.FontFamily]
  1208. if !familyNameOk {
  1209. tmpFamilyName = "宋体"
  1210. }
  1211. familyName = tmpFamilyName
  1212. }
  1213. if isUnderline {
  1214. underlineStyle = "single"
  1215. }
  1216. //VertAlign取值:
  1217. //BASELINE、superscript、subscript
  1218. return &excelize.Font{
  1219. Bold: isBold,
  1220. Italic: isItalic,
  1221. Underline: underlineStyle,
  1222. Family: familyName,
  1223. Size: float64(fontSize),
  1224. Strike: isUnderline,
  1225. Color: cellInfo.FontColor,
  1226. VertAlign: "",
  1227. }
  1228. }
  1229. // getExcelizeAlignmentConf 获取表格单元格排列配置
  1230. func getExcelizeAlignmentConf(cellInfo LuckySheetDataValue) *excelize.Alignment {
  1231. //自动换行
  1232. isWrapText := false
  1233. if cellInfo.TextBeak == 2 {
  1234. isWrapText = true
  1235. }
  1236. rotateText := 0
  1237. //if cellInfo.RotateText != `` {
  1238. // convSize, _ := strconv.Atoi(cellInfo.RotateText)
  1239. // if convSize > 0 {
  1240. // rotateText = convSize
  1241. // }
  1242. //}
  1243. return &excelize.Alignment{
  1244. Horizontal: LuckyHorizontalMap[cellInfo.HorizontalType],
  1245. //Indent: 0,
  1246. //JustifyLastLine: false,
  1247. //ReadingOrder: 0,
  1248. //RelativeIndent: 0,
  1249. //ShrinkToFit: false,
  1250. TextRotation: rotateText,
  1251. Vertical: LuckyVerticalMap[cellInfo.VerticalType],
  1252. WrapText: isWrapText,
  1253. }
  1254. }
  1255. // getColor 获取hex颜色
  1256. func getColor(bgStr string) string {
  1257. if strings.Contains(bgStr, "(") {
  1258. arr := strings.Split(bgStr, ",")
  1259. if len(arr) != 3 {
  1260. return bgStr
  1261. }
  1262. // 第一位
  1263. tmpFirstArr := strings.Split(arr[0], "(")
  1264. arr[0] = tmpFirstArr[len(tmpFirstArr)-1]
  1265. // 最后一位
  1266. tmpLastArr := strings.Split(arr[2], ")")
  1267. arr[2] = tmpLastArr[0]
  1268. rgbArr := make([]int64, 0)
  1269. for _, v := range arr {
  1270. tmpInt, err := strconv.Atoi(utils.TrimStr(v))
  1271. if err != nil {
  1272. return bgStr
  1273. }
  1274. rgbArr = append(rgbArr, int64(tmpInt))
  1275. }
  1276. rgb := RGB{
  1277. rgbArr[0],
  1278. rgbArr[1],
  1279. rgbArr[2],
  1280. }
  1281. bgStr = "" + rgb.Rgb2Hex().Str
  1282. }
  1283. return bgStr
  1284. }
  1285. // GetTableDataByCustomData 通过自定义表格数据获取表格数据
  1286. func GetTableDataByCustomData(excelType int, data request.TableDataReq) (selfTableData TableData, err error) {
  1287. tableDataList := make([][]LuckySheetDataValue, 0)
  1288. mergeList := make([]TableDataMerge, 0)
  1289. // 指标数
  1290. lenEdb := len(data.Data)
  1291. if lenEdb <= 0 {
  1292. return
  1293. }
  1294. // 日期数
  1295. lenCol := len(data.Data[0].Data)
  1296. if lenCol <= 0 {
  1297. return
  1298. }
  1299. // 指标列:1;指标行:2
  1300. if excelType == 1 {
  1301. mergeList = append(mergeList, TableDataMerge{
  1302. StartRowIndex: 0,
  1303. StartColumnIndex: 0,
  1304. MergeRowNum: 1,
  1305. MergeColumnNum: 0,
  1306. })
  1307. // 第一行
  1308. {
  1309. firstCol := make([]LuckySheetDataValue, 0)
  1310. firstCol = append(firstCol, LuckySheetDataValue{
  1311. Value: "日期",
  1312. Monitor: "日期",
  1313. MergeCell: LuckySheetDataConfigMerge{
  1314. Row: 0, //行数
  1315. Column: 0, //列数
  1316. Rs: 2, //合并的行数
  1317. Cs: 1, //合并的列数
  1318. },
  1319. })
  1320. for _, v := range data.Data {
  1321. edbName := v.EdbName
  1322. if v.EdbAliasName != `` {
  1323. edbName = v.EdbAliasName
  1324. }
  1325. firstCol = append(firstCol, LuckySheetDataValue{
  1326. Value: edbName,
  1327. Monitor: edbName,
  1328. MergeCell: LuckySheetDataConfigMerge{},
  1329. })
  1330. }
  1331. tableDataList = append(tableDataList, firstCol)
  1332. }
  1333. // 第二行
  1334. {
  1335. secondCol := make([]LuckySheetDataValue, 0)
  1336. secondCol = append(secondCol, LuckySheetDataValue{})
  1337. for _, v := range data.Data {
  1338. name := v.Unit + " / " + v.Frequency
  1339. secondCol = append(secondCol, LuckySheetDataValue{
  1340. Value: name,
  1341. Monitor: name,
  1342. MergeCell: LuckySheetDataConfigMerge{},
  1343. })
  1344. }
  1345. tableDataList = append(tableDataList, secondCol)
  1346. }
  1347. // 开始数据了
  1348. {
  1349. for i := 0; i < lenCol; i++ {
  1350. dataCol := make([]LuckySheetDataValue, 0)
  1351. // 日期
  1352. dataCol = append(dataCol, LuckySheetDataValue{
  1353. Value: data.Data[0].Data[i].DataTime,
  1354. Monitor: data.Data[0].Data[i].DataTime,
  1355. MergeCell: LuckySheetDataConfigMerge{},
  1356. })
  1357. // 数据值
  1358. for _, v := range data.Data {
  1359. dataCol = append(dataCol, LuckySheetDataValue{
  1360. Value: v.Data[i].Value,
  1361. Monitor: v.Data[i].ShowValue,
  1362. MergeCell: LuckySheetDataConfigMerge{},
  1363. })
  1364. }
  1365. tableDataList = append(tableDataList, dataCol)
  1366. }
  1367. }
  1368. // 开始文本行了
  1369. {
  1370. for _, textColList := range data.TextRowData {
  1371. dataCol := make([]LuckySheetDataValue, 0)
  1372. for _, v := range textColList {
  1373. dataCol = append(dataCol, LuckySheetDataValue{
  1374. Value: v.Value,
  1375. Monitor: v.ShowValue,
  1376. MergeCell: LuckySheetDataConfigMerge{},
  1377. })
  1378. }
  1379. tableDataList = append(tableDataList, dataCol)
  1380. }
  1381. }
  1382. } else {
  1383. // 指标行
  1384. mergeList = append(mergeList, TableDataMerge{
  1385. StartRowIndex: 0,
  1386. StartColumnIndex: 0,
  1387. MergeRowNum: 0,
  1388. MergeColumnNum: 1,
  1389. })
  1390. // 第一行
  1391. {
  1392. firstCol := make([]LuckySheetDataValue, 0)
  1393. firstCol = append(firstCol, LuckySheetDataValue{
  1394. Value: "日期",
  1395. Monitor: "日期",
  1396. MergeCell: LuckySheetDataConfigMerge{
  1397. Row: 0, //行数
  1398. Column: 0, //列数
  1399. Rs: 1, //合并的行数
  1400. Cs: 2, //合并的列数
  1401. },
  1402. })
  1403. firstCol = append(firstCol, LuckySheetDataValue{})
  1404. // 日期列
  1405. for _, v := range data.Data[0].Data {
  1406. firstCol = append(firstCol, LuckySheetDataValue{
  1407. Value: v.DataTime,
  1408. Monitor: v.DataTime,
  1409. MergeCell: LuckySheetDataConfigMerge{},
  1410. })
  1411. }
  1412. // 文本列
  1413. for _, textColList := range data.TextRowData {
  1414. firstCol = append(firstCol, LuckySheetDataValue{
  1415. Value: textColList[0].Value,
  1416. Monitor: textColList[0].ShowValue,
  1417. MergeCell: LuckySheetDataConfigMerge{},
  1418. })
  1419. }
  1420. tableDataList = append(tableDataList, firstCol)
  1421. }
  1422. // 日期列+文本列+两列表头(日期这个文案表头)
  1423. //colLen := lenCol+2+len(data.TextRowData)
  1424. for i := 0; i < lenEdb; i++ {
  1425. dataCol := make([]LuckySheetDataValue, 0)
  1426. // 指标信息
  1427. tmpEdbInfo := data.Data[i]
  1428. // 指标名称
  1429. {
  1430. edbName := tmpEdbInfo.EdbName
  1431. if tmpEdbInfo.EdbAliasName != `` {
  1432. edbName = tmpEdbInfo.EdbAliasName
  1433. }
  1434. dataCol = append(dataCol, LuckySheetDataValue{
  1435. Value: edbName,
  1436. Monitor: edbName,
  1437. MergeCell: LuckySheetDataConfigMerge{},
  1438. })
  1439. }
  1440. // 指标单位、频度
  1441. {
  1442. name := tmpEdbInfo.Unit + " / " + tmpEdbInfo.Frequency
  1443. dataCol = append(dataCol, LuckySheetDataValue{
  1444. Value: name,
  1445. Monitor: name,
  1446. MergeCell: LuckySheetDataConfigMerge{},
  1447. })
  1448. }
  1449. // 指标数据列
  1450. for _, tmpData := range tmpEdbInfo.Data {
  1451. dataCol = append(dataCol, LuckySheetDataValue{
  1452. Value: tmpData.Value,
  1453. Monitor: tmpData.ShowValue,
  1454. MergeCell: LuckySheetDataConfigMerge{},
  1455. })
  1456. }
  1457. // 文本列
  1458. for _, textColList := range data.TextRowData {
  1459. dataCol = append(dataCol, LuckySheetDataValue{
  1460. Value: textColList[i+1].Value,
  1461. Monitor: textColList[i+1].ShowValue,
  1462. MergeCell: LuckySheetDataConfigMerge{},
  1463. })
  1464. }
  1465. tableDataList = append(tableDataList, dataCol)
  1466. }
  1467. }
  1468. selfTableData.MergeList = mergeList
  1469. selfTableData.TableDataList = tableDataList
  1470. return
  1471. }
  1472. // GetTableDataByMixedTableData 通过混合表格数据获取表格数据
  1473. func GetTableDataByMixedTableData(config [][]request.MixedTableCellDataReq) (selfTableData TableData, err error) {
  1474. tableDataList := make([][]LuckySheetDataValue, 0)
  1475. mergeList := make([]TableDataMerge, 0)
  1476. // 开始文本行了
  1477. {
  1478. for _, row := range config {
  1479. dataCol := make([]LuckySheetDataValue, 0)
  1480. for _, cell := range row {
  1481. dataCol = append(dataCol, LuckySheetDataValue{
  1482. Value: cell.Value,
  1483. Monitor: cell.ShowValue,
  1484. MergeCell: LuckySheetDataConfigMerge{},
  1485. })
  1486. }
  1487. tableDataList = append(tableDataList, dataCol)
  1488. }
  1489. }
  1490. selfTableData.MergeList = mergeList
  1491. selfTableData.TableDataList = tableDataList
  1492. return
  1493. }