bootstrap-table-export.js 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. /**
  2. * @author zhixin wen <wenzhixin2010@gmail.com>
  3. * extensions: https://github.com/hhurz/tableExport.jquery.plugin
  4. */
  5. const Utils = $.fn.bootstrapTable.utils
  6. const TYPE_NAME = {
  7. json: 'JSON',
  8. xml: 'XML',
  9. png: 'PNG',
  10. csv: 'CSV',
  11. txt: 'TXT',
  12. sql: 'SQL',
  13. doc: 'MS-Word',
  14. excel: 'MS-Excel',
  15. xlsx: 'MS-Excel (OpenXML)',
  16. powerpoint: 'MS-Powerpoint',
  17. pdf: 'PDF'
  18. }
  19. $.extend($.fn.bootstrapTable.defaults, {
  20. showExport: false,
  21. exportDataType: 'basic', // basic, all, selected
  22. exportTypes: ['json', 'xml', 'csv', 'txt', 'sql', 'excel'],
  23. exportOptions: {
  24. onCellHtmlData (cell, rowIndex, colIndex, htmlData) {
  25. if (cell.is('th')) {
  26. return cell.find('.th-inner').text()
  27. }
  28. return htmlData
  29. }
  30. },
  31. exportFooter: false
  32. })
  33. $.extend($.fn.bootstrapTable.columnDefaults, {
  34. forceExport: false,
  35. forceHide: false
  36. })
  37. $.extend($.fn.bootstrapTable.defaults.icons, {
  38. export: {
  39. bootstrap3: 'glyphicon-export icon-share',
  40. bootstrap5: 'bi-download',
  41. materialize: 'file_download',
  42. 'bootstrap-table': 'icon-download'
  43. }[$.fn.bootstrapTable.theme] || 'fa-download'
  44. })
  45. $.extend($.fn.bootstrapTable.locales, {
  46. formatExport () {
  47. return 'Export data'
  48. }
  49. })
  50. $.extend($.fn.bootstrapTable.defaults, $.fn.bootstrapTable.locales)
  51. $.fn.bootstrapTable.methods.push('exportTable')
  52. $.extend($.fn.bootstrapTable.defaults, {
  53. // eslint-disable-next-line no-unused-vars
  54. onExportSaved (exportedRows) {
  55. return false
  56. }
  57. })
  58. $.extend($.fn.bootstrapTable.Constructor.EVENTS, {
  59. 'export-saved.bs.table': 'onExportSaved'
  60. })
  61. $.BootstrapTable = class extends $.BootstrapTable {
  62. initToolbar (...args) {
  63. const o = this.options
  64. let exportTypes = o.exportTypes
  65. this.showToolbar = this.showToolbar || o.showExport
  66. if (this.options.showExport) {
  67. if (typeof exportTypes === 'string') {
  68. const types = exportTypes.slice(1, -1).replace(/ /g, '').split(',')
  69. exportTypes = types.map(t => t.slice(1, -1))
  70. }
  71. this.$export = this.$toolbar.find('>.columns div.export')
  72. if (this.$export.length) {
  73. this.updateExportButton()
  74. return
  75. }
  76. this.buttons = Object.assign(this.buttons, {
  77. export: {
  78. html:
  79. (() => {
  80. if (exportTypes.length === 1) {
  81. return `
  82. <div class="export ${this.constants.classes.buttonsDropdown}"
  83. data-type="${exportTypes[0]}">
  84. <button class="${this.constants.buttonsClass}"
  85. aria-label="Export"
  86. type="button"
  87. title="${o.formatExport()}">
  88. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.export) : ''}
  89. ${o.showButtonText ? o.formatExport() : ''}
  90. </button>
  91. </div>
  92. `
  93. }
  94. const html = []
  95. html.push(`
  96. <div class="export ${this.constants.classes.buttonsDropdown}">
  97. <button class="${this.constants.buttonsClass} dropdown-toggle"
  98. aria-label="Export"
  99. ${this.constants.dataToggle}="dropdown"
  100. type="button"
  101. title="${o.formatExport()}">
  102. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.export) : ''}
  103. ${o.showButtonText ? o.formatExport() : ''}
  104. ${this.constants.html.dropdownCaret}
  105. </button>
  106. ${this.constants.html.toolbarDropdown[0]}
  107. `)
  108. for (const type of exportTypes) {
  109. if (TYPE_NAME.hasOwnProperty(type)) {
  110. const $item = $(Utils.sprintf(this.constants.html.pageDropdownItem, '', TYPE_NAME[type]))
  111. $item.attr('data-type', type)
  112. html.push($item.prop('outerHTML'))
  113. }
  114. }
  115. html.push(this.constants.html.toolbarDropdown[1], '</div>')
  116. return html.join('')
  117. })
  118. }
  119. })
  120. }
  121. super.initToolbar(...args)
  122. this.$export = this.$toolbar.find('>.columns div.export')
  123. if (!this.options.showExport) {
  124. return
  125. }
  126. this.updateExportButton()
  127. this.$export.find('[data-type]').click(e => {
  128. e.preventDefault()
  129. const type = $(e.currentTarget).data('type')
  130. const exportOptions = {
  131. type,
  132. escape: false
  133. }
  134. this.exportTable(exportOptions)
  135. })
  136. this.handleToolbar()
  137. }
  138. handleToolbar () {
  139. if (!this.$export) {
  140. return
  141. }
  142. if (super.handleToolbar) {
  143. super.handleToolbar()
  144. }
  145. }
  146. exportTable (options) {
  147. const o = this.options
  148. const stateField = this.header.stateField
  149. const isCardView = o.cardView
  150. const doExport = callback => {
  151. if (stateField) {
  152. this.hideColumn(stateField)
  153. }
  154. if (isCardView) {
  155. this.toggleView()
  156. }
  157. this.columns.forEach(row => {
  158. if (row.forceHide) {
  159. this.hideColumn(row.field)
  160. }
  161. })
  162. const data = this.getData()
  163. if (o.detailView && o.detailViewIcon) {
  164. const detailViewIndex = o.detailViewAlign === 'left' ? 0 : this.getVisibleFields().length + Utils.getDetailViewIndexOffset(this.options)
  165. o.exportOptions.ignoreColumn = [detailViewIndex].concat(o.exportOptions.ignoreColumn || [])
  166. }
  167. if (o.exportFooter) {
  168. const $footerRow = this.$tableFooter.find('tr').first()
  169. const footerData = {}
  170. const footerHtml = []
  171. $.each($footerRow.children(), (index, footerCell) => {
  172. const footerCellHtml = $(footerCell).children('.th-inner').first().html()
  173. footerData[this.columns[index].field] = footerCellHtml === '&nbsp;' ? null : footerCellHtml
  174. // grab footer cell text into cell index-based array
  175. footerHtml.push(footerCellHtml)
  176. })
  177. this.$body.append(this.$body.children().last()[0].outerHTML)
  178. const $lastTableRow = this.$body.children().last()
  179. $.each($lastTableRow.children(), (index, lastTableRowCell) => {
  180. $(lastTableRowCell).html(footerHtml[index])
  181. })
  182. }
  183. const hiddenColumns = this.getHiddenColumns()
  184. hiddenColumns.forEach(row => {
  185. if (row.forceExport) {
  186. this.showColumn(row.field)
  187. }
  188. })
  189. if (typeof o.exportOptions.fileName === 'function') {
  190. options.fileName = o.exportOptions.fileName()
  191. }
  192. this.$el.tableExport($.extend({
  193. onAfterSaveToFile: () => {
  194. if (o.exportFooter) {
  195. this.load(data)
  196. }
  197. if (stateField) {
  198. this.showColumn(stateField)
  199. }
  200. if (isCardView) {
  201. this.toggleView()
  202. }
  203. hiddenColumns.forEach(row => {
  204. if (row.forceExport) {
  205. this.hideColumn(row.field)
  206. }
  207. })
  208. this.columns.forEach(row => {
  209. if (row.forceHide) {
  210. this.showColumn(row.field)
  211. }
  212. })
  213. if (callback) callback()
  214. }
  215. }, o.exportOptions, options))
  216. }
  217. if (o.exportDataType === 'all' && o.pagination) {
  218. const eventName = o.sidePagination === 'server' ?
  219. 'post-body.bs.table' : 'page-change.bs.table'
  220. const virtualScroll = this.options.virtualScroll
  221. this.$el.one(eventName, () => {
  222. setTimeout(() => {
  223. doExport(() => {
  224. this.options.virtualScroll = virtualScroll
  225. this.togglePagination()
  226. })
  227. }, 0)
  228. })
  229. this.options.virtualScroll = false
  230. this.togglePagination()
  231. this.trigger('export-saved', this.getData())
  232. } else if (o.exportDataType === 'selected') {
  233. let data = this.getData()
  234. let selectedData = this.getSelections()
  235. const pagination = o.pagination
  236. if (!selectedData.length) {
  237. return
  238. }
  239. if (o.sidePagination === 'server') {
  240. data = {
  241. total: o.totalRows,
  242. [this.options.dataField]: data
  243. }
  244. selectedData = {
  245. total: selectedData.length,
  246. [this.options.dataField]: selectedData
  247. }
  248. }
  249. this.load(selectedData)
  250. if (pagination) {
  251. this.togglePagination()
  252. }
  253. doExport(() => {
  254. if (pagination) {
  255. this.togglePagination()
  256. }
  257. this.load(data)
  258. })
  259. this.trigger('export-saved', selectedData)
  260. } else {
  261. doExport()
  262. this.trigger('export-saved', this.getData(true))
  263. }
  264. }
  265. updateSelected () {
  266. super.updateSelected()
  267. this.updateExportButton()
  268. }
  269. updateExportButton () {
  270. if (this.options.exportDataType === 'selected') {
  271. this.$export.find('> button')
  272. .prop('disabled', !this.getSelections().length)
  273. }
  274. }
  275. }