bootstrap-table-export.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  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. if (typeof o.exportOptions === 'string') {
  72. o.exportOptions = Utils.calculateObjectValue(null, o.exportOptions)
  73. }
  74. this.$export = this.$toolbar.find('>.columns div.export')
  75. if (this.$export.length) {
  76. this.updateExportButton()
  77. return
  78. }
  79. this.buttons = Object.assign(this.buttons, {
  80. export: {
  81. html:
  82. (() => {
  83. if (exportTypes.length === 1) {
  84. return `
  85. <div class="export ${this.constants.classes.buttonsDropdown}"
  86. data-type="${exportTypes[0]}">
  87. <button class="${this.constants.buttonsClass}"
  88. aria-label="Export"
  89. type="button"
  90. title="${o.formatExport()}">
  91. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.export) : ''}
  92. ${o.showButtonText ? o.formatExport() : ''}
  93. </button>
  94. </div>
  95. `
  96. }
  97. const html = []
  98. html.push(`
  99. <div class="export ${this.constants.classes.buttonsDropdown}">
  100. <button class="${this.constants.buttonsClass} dropdown-toggle"
  101. aria-label="Export"
  102. ${this.constants.dataToggle}="dropdown"
  103. type="button"
  104. title="${o.formatExport()}">
  105. ${o.showButtonIcons ? Utils.sprintf(this.constants.html.icon, o.iconsPrefix, o.icons.export) : ''}
  106. ${o.showButtonText ? o.formatExport() : ''}
  107. ${this.constants.html.dropdownCaret}
  108. </button>
  109. ${this.constants.html.toolbarDropdown[0]}
  110. `)
  111. for (const type of exportTypes) {
  112. if (TYPE_NAME.hasOwnProperty(type)) {
  113. const $item = $(Utils.sprintf(this.constants.html.pageDropdownItem, '', TYPE_NAME[type]))
  114. $item.attr('data-type', type)
  115. html.push($item.prop('outerHTML'))
  116. }
  117. }
  118. html.push(this.constants.html.toolbarDropdown[1], '</div>')
  119. return html.join('')
  120. })
  121. }
  122. })
  123. }
  124. super.initToolbar(...args)
  125. this.$export = this.$toolbar.find('>.columns div.export')
  126. if (!this.options.showExport) {
  127. return
  128. }
  129. this.updateExportButton()
  130. let $exportButtons = this.$export.find('[data-type]')
  131. if (exportTypes.length === 1) {
  132. $exportButtons = this.$export
  133. }
  134. $exportButtons.click(e => {
  135. e.preventDefault()
  136. const type = $(e.currentTarget).data('type')
  137. const exportOptions = {
  138. type,
  139. escape: false
  140. }
  141. this.exportTable(exportOptions)
  142. })
  143. this.handleToolbar()
  144. }
  145. handleToolbar () {
  146. if (!this.$export) {
  147. return
  148. }
  149. if (super.handleToolbar) {
  150. super.handleToolbar()
  151. }
  152. }
  153. exportTable (options) {
  154. const o = this.options
  155. const stateField = this.header.stateField
  156. const isCardView = o.cardView
  157. const doExport = callback => {
  158. if (stateField) {
  159. this.hideColumn(stateField)
  160. }
  161. if (isCardView) {
  162. this.toggleView()
  163. }
  164. this.columns.forEach(row => {
  165. if (row.forceHide) {
  166. this.hideColumn(row.field)
  167. }
  168. })
  169. const data = this.getData()
  170. if (o.detailView && o.detailViewIcon) {
  171. const detailViewIndex = o.detailViewAlign === 'left' ? 0 : this.getVisibleFields().length + Utils.getDetailViewIndexOffset(this.options)
  172. o.exportOptions.ignoreColumn = [detailViewIndex].concat(o.exportOptions.ignoreColumn || [])
  173. }
  174. if (o.exportFooter) {
  175. const $footerRow = this.$tableFooter.find('tr').first()
  176. const footerData = {}
  177. const footerHtml = []
  178. $.each($footerRow.children(), (index, footerCell) => {
  179. const footerCellHtml = $(footerCell).children('.th-inner').first().html()
  180. footerData[this.columns[index].field] = footerCellHtml === '&nbsp;' ? null : footerCellHtml
  181. // grab footer cell text into cell index-based array
  182. footerHtml.push(footerCellHtml)
  183. })
  184. this.$body.append(this.$body.children().last()[0].outerHTML)
  185. const $lastTableRow = this.$body.children().last()
  186. $.each($lastTableRow.children(), (index, lastTableRowCell) => {
  187. $(lastTableRowCell).html(footerHtml[index])
  188. })
  189. }
  190. const hiddenColumns = this.getHiddenColumns()
  191. hiddenColumns.forEach(row => {
  192. if (row.forceExport) {
  193. this.showColumn(row.field)
  194. }
  195. })
  196. if (typeof o.exportOptions.fileName === 'function') {
  197. options.fileName = o.exportOptions.fileName()
  198. }
  199. this.$el.tableExport($.extend({
  200. onAfterSaveToFile: () => {
  201. if (o.exportFooter) {
  202. this.load(data)
  203. }
  204. if (stateField) {
  205. this.showColumn(stateField)
  206. }
  207. if (isCardView) {
  208. this.toggleView()
  209. }
  210. hiddenColumns.forEach(row => {
  211. if (row.forceExport) {
  212. this.hideColumn(row.field)
  213. }
  214. })
  215. this.columns.forEach(row => {
  216. if (row.forceHide) {
  217. this.showColumn(row.field)
  218. }
  219. })
  220. if (callback) callback()
  221. }
  222. }, o.exportOptions, options))
  223. }
  224. if (o.exportDataType === 'all' && o.pagination) {
  225. const eventName = o.sidePagination === 'server' ?
  226. 'post-body.bs.table' : 'page-change.bs.table'
  227. const virtualScroll = this.options.virtualScroll
  228. this.$el.one(eventName, () => {
  229. setTimeout(() => {
  230. doExport(() => {
  231. this.options.virtualScroll = virtualScroll
  232. this.togglePagination()
  233. })
  234. }, 0)
  235. })
  236. this.options.virtualScroll = false
  237. this.togglePagination()
  238. this.trigger('export-saved', this.getData())
  239. } else if (o.exportDataType === 'selected') {
  240. let data = this.getData()
  241. let selectedData = this.getSelections()
  242. const pagination = o.pagination
  243. if (!selectedData.length) {
  244. return
  245. }
  246. if (o.sidePagination === 'server') {
  247. data = {
  248. total: o.totalRows,
  249. [this.options.dataField]: data
  250. }
  251. selectedData = {
  252. total: selectedData.length,
  253. [this.options.dataField]: selectedData
  254. }
  255. }
  256. this.load(selectedData)
  257. if (pagination) {
  258. this.togglePagination()
  259. }
  260. doExport(() => {
  261. if (pagination) {
  262. this.togglePagination()
  263. }
  264. this.load(data)
  265. })
  266. this.trigger('export-saved', selectedData)
  267. } else {
  268. doExport()
  269. this.trigger('export-saved', this.getData(true))
  270. }
  271. }
  272. updateSelected () {
  273. super.updateSelected()
  274. this.updateExportButton()
  275. }
  276. updateExportButton () {
  277. if (this.options.exportDataType === 'selected') {
  278. this.$export.find('> button')
  279. .prop('disabled', !this.getSelections().length)
  280. }
  281. }
  282. }