This tutorial shows how to create an HTML5 JavaScript application that uses the LEADTOOLS SDK to load and save a sheet file (.xlsx, .xls) in the HTML5 JavaScript Sheet Editor.
Overview | |
---|---|
Summary | This tutorial covers how to use LEADTOOLS Document Viewer SDK technology in an HTML5 JavaScript Application. |
Completion Time | 30 minutes |
Visual Studio Project | Download tutorial project (104 KB) |
Platform | JS Web Application |
IDE | Visual Studio Code - Client |
Development License | Download LEADTOOLS |
Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License - HTML5 JavaScript tutorial, before working on the Load and Save Files with the Sheet Editor - HTML5 JavaScript tutorial.
This tutorial makes use of http-server
, a console command for running a static file server. To install http-server
first install Node.js
and then install http-server
.
Start with a copy of the project created in the Add References and Set a License - HTML5 JavaScript tutorial. If that project is unavailable, follow the steps in that tutorial to create it.
Inside the project folder create a new file, style.css
, which will handle the body layout.
The references needed depend upon the purpose of the project. References can be added by .js
files located at <INSTALL_DIR>\LEADTOOLS23\Bin\JS
.
For this project, the following references are needed:
Leadtools.js
Leadtools.Annotations.Automation.js
Leadtools.Annotations.Engine.js
Leadtools.Document.js
Leadtools.Document.SheetEditor.js
Make sure to copy these files to the project's lib
folder.
For a complete list of which JS files are required for your application, refer to Files to be Included with your Application
The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details including tutorials for different platforms, refer to Setting a Runtime License.
There are two types of runtime licenses:
Note
Adding LEADTOOLS references and setting a license are covered in more detail in the Add References and Set a License - HTML5 JavaScript tutorial.
With the project created, dependencies added, and the license set, coding can begin.
Open the index.html
file located in the project folder. Add the following lines in the <head>
tag to import the JS files and attach the dependencies to the index.html
page. Then add the following <head>
and <body>
elements to the <html>
element of the index.html
page, which will be used to load the required dependencies and display the sheet editor.
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>LEADTOOLS Sheet Editor Tutorial</title>
<link rel="shortcut icon" type="image/x-icon" href="./resources/favicon.ico" />
<script src="./resources/lib/Leadtools.js"></script>
<script>
if (lt.LTHelper.browser == lt.LTBrowser.internetExplorer)
alert("IE is not supported, please use a different browser to run this demo");
</script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"
crossorigin="anonymous"></script>
<script crossorigin src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<link rel='stylesheet' href='./resources/css/lt_leadsheet.css' />
<link rel="stylesheet" href="./resources/css/style.css" />
<script src="./resources/lib/Leadtools.Annotations.Engine.js"></script>
<script src="./resources/lib/Leadtools.Annotations.Automation.js"></script>
<script src="./resources/lib/Leadtools.Document.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-mousewheel/3.1.13/jquery.mousewheel.min.js" integrity="sha512-rCjfoab9CVKOH/w/T6GbBxnAH5Azhy4+q1EXW5XEURefHbIkRbQ++ZR+GBClo3/d3q583X/gO4FKmOFuhkKrdA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<script src="./resources/lib/Leadtools.Document.SheetEditor.js"></script>
<script src="/src/app.js"></script>
</head>
<body>
<div style="height: 100vh; width: 100%; display: flex; flex-direction: column;" id="div_container">
<!-- Command Bar -->
<div class="commandbar" id="main-menu">
<!-- Titlebar -->
<div class="titlebar-frame">
<span>LEADTOOLS Sheet Editor Tutorial</span>
</div>
<!-- Toolbar -->
<div class="toolbar">
<span>
<!-- File Menu Items -->
<button id="load-from-file-button">Upload from File</button>
<button id="load-from-url-button">Upload from Url</button>
<button id="save-sheet-button">Save</button>
</span>
</div>
</div>
<!-- Sheet Editor -->
<div class="editor-body" id="editorWrapper" oncontextmenu="return false;">
<div class="inner-body" id="content"></div>
</div>
</div>
</body>
Open the style.css
file located in the project folder. Remove any default styling and add the below lines of code to the file:
body {
margin: 0;
background-color: white;
}
.commandbar {
display: flex;
flex-direction: column;
width: 100%;
font-size: 14px;
font-family: "Arial";
flex-shrink: 0;
background-color: #f8f8f8;
}
.titlebar-frame {
display: flex;
flex-direction: row;
color: white;
background-color: royalblue;
padding-top: 4px;
padding-bottom: 4px;
padding-left: 34px;
padding-right: 30px;
margin-bottom: 4px;
border-bottom: 1px solid royalblue;
flex-shrink: 0;
white-space: nowrap;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
}
.titlebar-frame span {
align-self: center;
font-family: "Arial";
font-weight: 700;
font-size: 18px;
}
.noselect {
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
}
.toolbar {
display: flex;
flex-direction: row;
padding-left: 35px;
padding-right: 20px;
padding-top: 5px;
padding-bottom: 5px;
white-space: nowrap;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Safari */
-khtml-user-select: none; /* Konqueror HTML */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none; /* Non-prefixed version, currently supported by Chrome and Opera */
font-size: 14px;
font-family: "Arial";
flex-shrink: 0;
}
.editor-body {
height: 100%;
width: 100%;
flex: 1 1 auto;
overflow: hidden;
background-color: #e8e8e8;
padding-left: 4px;
padding-top: 0px;
padding-right: 4px;
padding-bottom: 4px;
}
.inner-body {
background-color: white;
width: 100%;
height: 100%;
overflow: hidden;
}
.cell-creator {
width: 10px;
height: 10px;
margin: 2px;
border: 1px solid black;
}
.cell-selected {
border-color: royalblue;
background: rgba(0, 0, 255, 0.2);
}
.cell-hidden {
display: none;
}
.grid-wrapper {
padding: 10px;
}
.btn {
min-width: 75px;
}
/* Full width */
.full-width {
width: 100%;
}
The sheet editor also requires the lt_leadsheet.css
css file that can be found in <INSTALL_DIR>\LEADTOOLS23\Examples\Editors\JS\SheetEditorDemo\site\css
. Copy and place this file into your project folder.
Open the app.js
file located in the project folder. Add the below code to create functionality for the buttons in index.html
that allow us to load and save sheet (.xlsx, .xls) files.
window.onload = () => {
// You can set the directory in which to check the license (client side)
// commented out, because we're using the default value ("./LEADTOOLS")
//lt.LTHelper.licenseDirectory = "";
lt.RasterSupport.setLicenseUri("https://demo.leadtools.com/licenses/js/LEADTOOLSEVAL.txt", "EVAL", function (setLicenseResult) {
if (setLicenseResult.result) {
console.log("LEADTOOLS client license set successfully");
verifyService();
init();
} else {
const msg = "No LEADTOOLS License\n\nYour license file is missing, invalid or expired. LEADTOOLS will not function. Please contact LEAD Sales for information on obtaining a valid license.";
alert(msg);
console.log(msg);
}
});
const content = document.getElementById('content');
const editor = lt.Document.SheetEditor.SheetEditorFactory.createSheetEditor(new lt.Document.SheetEditor.SheetEditorCreateOptions(content));
let saveButton = document.getElementById('save-sheet-button');
saveButton.addEventListener("click", () => { onSaveSheetClick(editor); })
let loadFromFileButton = document.getElementById('load-from-file-button');
loadFromFileButton.addEventListener("click", () => { onLoadFromFileClick(editor); })
let loadFromUrlButton = document.getElementById('load-from-url-button');
loadFromUrlButton.addEventListener("click", () => { onLoadFromUrlClick(editor); })
}
let onSaveSheetClick = (editor) => {
ele = saveSheet(editor);
ele.click();
}
let onLoadFromFileClick = (editor) => {
ele = loadSheetFromFile(editor);
ele.click();
}
let onLoadFromUrlClick = (editor) => {
loadSheetFromUrl(editor);
}
let saveSheet = (editor) => {
const input = document.createElement('input');
const fileName = "output.xlsx";
let promise = null;
promise = editor.getWorkbook().exportWorkbook(fileName);
promise.then(name => {
})
.catch(err => {
let errMsg = err;
if (!!err.detail)
errMsg = err.detail;
alert(`There was an issue saving the document: ${errMsg}`);
});
return input;
}
let loadSheetFromFile = (editor) => {
const input = document.createElement('input');
input.type = 'file';
input.style.display = 'none';
input.accept = '.xls, .xlsx';
input.onchange = (e) => {
const files = input.files;
if (!files || !files.length)
return;
const file = files[0];
lt.Document.DocumentFactory.loadFromFile(file, null).then((doc) => {
editor.setDocument(doc);
}).catch((e) => {
alert(`There was an issue importing the document: ${e}`);
});
}
document.body.appendChild(input);
return input;
}
let loadSheetFromUrl = (editor) => {
// Default url for sheet file. Port # may need to be changed.
var url = "http://localhost:8080/resources/images/example_sheet.xlsx";
var userInput = "";
userInput = window.prompt(`Enter a Url to upload. \n\nNOTE: If no Url is entered, the default '${url}' will be used`);
if (userInput != undefined && userInput != "")
url = userInput;
console.log(`Attempting to load '${url}'...`);
lt.Document.DocumentFactory.loadFromUri(url, null).then((doc) => {
editor.setDocument(doc);
}).catch((e) => {
alert(`There was an issue importing the document: ${e}`);
});
}
let verifyService = async () => {
lt.Document.DocumentFactory.serviceHost = "http://localhost:30000";
lt.Document.DocumentFactory.servicePath = "";
lt.Document.DocumentFactory.serviceApiPath = "api";
try {
let result = await lt.Document.DocumentFactory.verifyService();
console.log("service connection verified!");
}
catch(err) {
console.log("error reaching LEADTOOLS DocumentService");
}
}
let init = () => {}
Before running the front end HTML5/JS Document Viewer, run the Document Service. The LEADTOOLS SDK installation provides three examples of the Document Service for the following platforms:
For instructions on how to set up and configure the Document Service, in the three platforms previously listed, refer to the steps in the Get Started with the Document Viewer Demo - HTML5 JavaScript tutorial.
For the purposes of this tutorial, the .NET Framework Document Service is used and it can be found here: <INSTALL_DIR>\LEADTOOLS23\Examples\Document\JS\DocumentServiceDotNet\net
.
Once you have the back-end Document Service running, open the Command Line and cd
into the project folder. Use the following command to run a static file server: http-server
The server should start and run on http://localhost:8080
. A message should appear in the console indicating all the ports that the server is available on.
To test, upload a document via file or url, make a change, and save the file.
This tutorial showed how to load and save a sheet file in an HTML5/JS Sheet Editor application.