Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import * as React from "react"
- import * as OfficeHelpers from "@microsoft/office-js-helpers"
- const tableName = `tableName`;
- const tableRange = "B1:E1";
- const excelHeaders = ["Firstname", "Lastname", "Age", "City"];
- const excelData = [["Mario", "Rossi", 40, "Milano"], ["Mario", "Verdi", 60, "Roma"], ["Gianni", "Neri", 50, "Catania"], ["Gianni", "Bianchi", 80, "Palermo"]];
- class App extends React.Component {
- constructor(props, context) {
- super(props, context)
- this.state = {
- slice: 0,
- }
- }
- useAddRows = (slice: number = excelData.length) => {
- Excel.run(context => {
- const _excelData = excelData.slice(0, slice)
- const currentWorksheet = context.workbook.worksheets.getItemOrNullObject(
- "Sheet1"
- )
- let excelTable = currentWorksheet.tables.getItemOrNullObject(tableName)
- excelTable.rows.load("values")
- excelTable.columns.load("values")
- return context.sync().then(() => {
- if (excelTable.isNullObject) {
- excelTable = currentWorksheet.tables.add(tableRange, true)
- excelTable.name = tableName
- excelTable.getHeaderRowRange().values = [excelHeaders]
- excelTable.rows.add(null, _excelData)
- } else {
- const tableRows = excelTable.rows.items.length
- const tableColumns = excelTable.columns.items.length
- const dataRows = _excelData.length
- const dataColumns = _excelData[0].length
- for (let i = tableRows - 1; i >= 0; i--) {
- // Deletes all table rows
- excelTable.rows.items[i].delete()
- }
- excelTable.rows.add(0, _excelData)
- }
- excelTable.getRange().format.autofitColumns()
- excelTable.getRange().format.autofitRows()
- return context.sync()
- })
- }).catch(function(error) {
- Debug.error(
- `ErrorCode: ${error.code}`,
- `ErrorMessage: ${error.message}`,
- `ErrorDebugInfo: ${error.debugInfo}`
- )
- if (error instanceof OfficeExtension.Error) {
- Debug.error("Debug info: " + JSON.stringify(error.debugInfo))
- }
- })
- }
- render() {
- const { slice } = this.state
- const styl = {
- dataSizeBtn: {
- padding: "2px 16px",
- },
- rowButtonsContainer: {
- display: "flex",
- justifyContent: "space-around",
- },
- }
- return (
- <div className="taskpane" style={{ paddingTop: "10px" }}>
- <div style={styl.rowButtonsContainer}>
- <button
- style={styl.dataSizeBtn}
- onClick={() => {
- this.useAddRows(1)
- }}
- >
- 1
- </button>
- <button
- style={styl.dataSizeBtn}
- onClick={() => {
- this.useAddRows(2)
- }}
- >
- 2
- </button>
- <button
- style={styl.dataSizeBtn}
- onClick={() => {
- this.useAddRows(3)
- }}
- >
- 3
- </button>
- <button
- style={styl.dataSizeBtn}
- onClick={() => {
- this.useAddRows(4)
- }}
- >
- 4
- </button>
- <button
- style={styl.dataSizeBtn}
- onClick={() => {
- const resultSet = Math.floor((Math.random() * 1000) % 5)
- Debug.print(`resultSet: ${resultSet}`)
- this.useAddRows(resultSet)
- }}
- >
- RAND
- </button>
- </div>
- </div>
- )
- }
- }
- }
Add Comment
Please, Sign In to add comment