Skip to content

Instantly share code, notes, and snippets.

@aspose-cells
Last active November 6, 2018 11:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save aspose-cells/87c05ec07dd1a65ac6fcdf2fa896b01e to your computer and use it in GitHub Desktop.
Save aspose-cells/87c05ec07dd1a65ac6fcdf2fa896b01e to your computer and use it in GitHub Desktop.
This Gist contains code snippets of examples of Aspose.Cells for Java.
This gist exceeds the recommended number of files (~10). To access all files, please clone this gist.
Aspose.Cells for Java - Examples
//The path to the documents directory
String dataDir = Utils.getDataDir(DeleteRedundantSpacesFromHtml.class);
//Sample Html containing redundant spaces after <br> tag
String html = "<html>"
+ "<body>"
+ "<table>"
+ "<tr>"
+ "<td>"
+ "<br> This is sample data"
+ "<br> This is sample data"
+ "<br> This is sample data"
+ "</td>"
+ "</tr>"
+ "</table>"
+ "</body>"
+ "</html>";
//Convert Html to byte array
byte[] byteArray = html.getBytes();
//Set Html load options and keep precision true
HTMLLoadOptions loadOptions = new HTMLLoadOptions(LoadFormat.HTML);
loadOptions.setDeleteRedundantSpaces(true);
//Convert byte array into stream
java.io.ByteArrayInputStream stream = new java.io.ByteArrayInputStream(byteArray);
//Create workbook from stream with Html load options
Workbook workbook = new Workbook(stream, loadOptions);
//Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
//Auto fit the sheet columns
worksheet.autoFitColumns();
//Save the workbook
workbook.save(dataDir + "output-" + loadOptions.getDeleteRedundantSpaces() + ".xlsx", SaveFormat.XLSX);
System.out.println("File saved");
//Create an instance of workbook
Workbook workbook = new Workbook();
//Access first worksheet from the collection
Worksheet worksheet = workbook.getWorksheets().get(0);
//Access cells A1 and A2
Cell a1 = worksheet.getCells().get("A1");
Cell a2 = worksheet.getCells().get("A2");
//Add simple text to cell A1 and text with quote prefix to cell A2
a1.putValue("sample");
a2.putValue("'sample");
//Print their string values, A1 and A2 both are same
System.out.println("String value of A1: " + a1.getStringValue());
System.out.println("String value of A2: " + a2.getStringValue());
//Access styles of cells A1 and A2
Style s1 = a1.getStyle();
Style s2 = a2.getStyle();
System.out.println();
//Check if A1 and A2 has a quote prefix
System.out.println("A1 has a quote prefix: " + s1.getQuotePrefix());
System.out.println("A2 has a quote prefix: " + s2.getQuotePrefix());
public static void main(String[] args) throws Exception {
//The path to the documents directory
String dataDir = Utils.getDataDir(FindReferenceCellsFromExternalConnection.class);
//Load workbook object
Workbook workbook = new Workbook(dataDir + "sample.xlsm");
//Check all the connections inside the workbook
for (int i = 0; i < workbook.getDataConnections().getCount(); i++)
{
ExternalConnection externalConnection = workbook.getDataConnections().get(i);
System.out.println("connection: " + externalConnection.getName());
PrintTables(workbook, externalConnection);
System.out.println();
}
}
public static void PrintTables(Workbook workbook, ExternalConnection ec)
{
//Iterate all the worksheets
for (int j = 0; j < workbook.getWorksheets().getCount(); j++)
{
Worksheet worksheet = workbook.getWorksheets().get(j);
//Check all the query tables in a worksheet
for (int k = 0; k < worksheet.getQueryTables().getCount(); k++)
{
QueryTable qt = worksheet.getQueryTables().get(k);
//Check if query table is related to this external connection
if (ec.getId() == qt.getConnectionId()
&& qt.getConnectionId() >= 0)
{
//Print the query table name and print its "Refers To" range
System.out.println("querytable " + qt.getName());
String n = qt.getName().replace('+', '_').replace('=', '_');
Name name = workbook.getWorksheets().getNames().get("'" + worksheet.getName() + "'!" + n);
if (name != null)
{
Range range = name.getRange();
if (range != null)
{
System.out.println("Refers To: " + range.getRefersTo());
}
}
}
}
//Iterate all the list objects in this worksheet
for (int k = 0; k < worksheet.getListObjects().getCount(); k++)
{
ListObject table = worksheet.getListObjects().get(k);
//Check the data source type if it is query table
if (table.getDataSourceType() == TableDataSourceType.QUERY_TABLE)
{
//Access the query table related to list object
QueryTable qt = table.getQueryTable();
//Check if query table is related to this external connection
if (ec.getId() == qt.getConnectionId()
&& qt.getConnectionId() >= 0)
{
//Print the query table name and print its refersto range
System.out.println("querytable " + qt.getName());
System.out.println("Table " + table.getDisplayName());
System.out.println("refersto: " + worksheet.getName() + "!" + CellsHelper.cellIndexToName(table.getStartRow(), table.getStartColumn()) + ":" + CellsHelper.cellIndexToName(table.getEndRow(), table.getEndColumn()));
}
}
}
}
}//end-PrintTables
// The path to the documents directory
String dataDir = Utils.getDataDir(KeepPrecisionOfLargeNumbers.class);
//Sample Html containing large number with digits greater than 15
String html = "<html>"
+ "<body>"
+ "<p>1234567890123456</p>"
+ "</body>"
+ "</html>";
//Convert Html to byte array
byte[] byteArray = html.getBytes();
//Set Html load options and keep precision true
HTMLLoadOptions loadOptions = new HTMLLoadOptions(LoadFormat.HTML);
loadOptions.setKeepPrecision(true);
//Convert byte array into stream
java.io.ByteArrayInputStream stream = new java.io.ByteArrayInputStream(byteArray);
//Create workbook from stream with Html load options
Workbook workbook = new Workbook(stream, loadOptions);
//Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
//Auto fit the sheet columns
worksheet.autoFitColumns();
//Save the workbook
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
System.out.println("File saved");
public static void main(String[] args) throws Exception {
// The path to the documents directory.
String dataDir = Utils.getDataDir(SmartMarkerGroupingImage.class);
SmartMarkerGroupingImage grouping = new SmartMarkerGroupingImage();
grouping.Execute(dataDir);
}
public void Execute(String dataDir) throws Exception {
//Get the image
Path path = Paths.get(dataDir + "sample1.png");
byte[] photo1 = Files.readAllBytes(path);
//Get the image
path = Paths.get(dataDir + "sample2.jpg");
byte[] photo2 = Files.readAllBytes(path);
//Create a new workbook and access its worksheet
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.getWorksheets().get(0);
//Set the standard row height to 35
worksheet.getCells().setStandardHeight(35);
//Set column widhts of D, E and F
worksheet.getCells().setColumnWidth(3, 20);
worksheet.getCells().setColumnWidth(4, 20);
worksheet.getCells().setColumnWidth(5, 40);
//Add the headings in columns D, E and F
worksheet.getCells().get("D1").putValue("Name");
Style st = worksheet.getCells().get("D1").getStyle();
st.getFont().setBold(true);
worksheet.getCells().get("D1").setStyle(st);
worksheet.getCells().get("E1").putValue("City");
worksheet.getCells().get("E1").setStyle(st);
worksheet.getCells().get("F1").putValue("Photo");
worksheet.getCells().get("F1").setStyle(st);
//Add smart marker tags in columns D, E, F
worksheet.getCells().get("D2").putValue("&=Person.Name(group:normal,skip:1)");
worksheet.getCells().get("E2").putValue("&=Person.City");
worksheet.getCells().get("F2").putValue("&=Person.Photo(Picture:FitToCell)");
//Create Persons objects with photos
ArrayList<Person> persons = new ArrayList<Person>();
persons.add(new Person("George", "New York", photo1));
persons.add(new Person("George", "New York", photo2));
persons.add(new Person("George", "New York", photo1));
persons.add(new Person("George", "New York", photo2));
persons.add(new Person("Johnson", "London", photo2));
persons.add(new Person("Johnson", "London", photo1));
persons.add(new Person("Johnson", "London", photo2));
persons.add(new Person("Simon", "Paris", photo1));
persons.add(new Person("Simon", "Paris", photo2));
persons.add(new Person("Simon", "Paris", photo1));
persons.add(new Person("Henry", "Sydney", photo2));
persons.add(new Person("Henry", "Sydney", photo1));
persons.add(new Person("Henry", "Sydney", photo2));
//Create a workbook designer
WorkbookDesigner designer = new WorkbookDesigner(workbook);
//Set the data source and process smart marker tags
designer.setDataSource("Person", persons);
designer.process();
//Save the workbook
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
System.out.println("File saved");
}
public class Person
{
//Create Name, City and Photo properties
private String m_Name;
private String m_City;
private byte[] m_Photo;
public Person(String name, String city, byte[] photo)
{
m_Name = name;
m_City = city;
m_Photo = photo;
}
public String getName() { return this.m_Name; }
public void setName(String name) { this.m_Name = name; }
public String getCity() { return this.m_City; }
public void setCity(String address) { this.m_City = address; }
public byte[] getPhoto() { return this.m_Photo; }
public void setAddress(byte[] photo) { this.m_Photo = photo; }
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load sample Excel file containing the chart.
Workbook wb = new Workbook(srcDir + "sampleCreateChartPDFWithDesiredPageSize.xlsx");
//Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
//Access first chart inside the worksheet.
Chart ch = ws.getCharts().get(0);
//Create chart pdf with desired page size.
ch.toPdf(outDir + "outputCreateChartPDFWithDesiredPageSize.pdf", 7, 7, PageLayoutAlignmentType.CENTER, PageLayoutAlignmentType.CENTER);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Converting integer enums to string enums
java.util.HashMap<Integer, String> cvTypes = new java.util.HashMap<Integer, String>();
cvTypes.put(CellValueType.IS_NUMERIC, "IsNumeric");
cvTypes.put(CellValueType.IS_STRING, "IsString");
//Load sample Excel file containing chart.
Workbook wb = new Workbook(srcDir + "sampleFindTypeOfXandYValuesOfPointsInChartSeries.xlsx");
//Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
//Access first chart.
Chart ch = ws.getCharts().get(0);
//Calculate chart data.
ch.calculate();
//Access first chart point in the first series.
ChartPoint pnt = ch.getNSeries().get(0).getPoints().get(0);
//Print the types of X and Y values of chart point.
System.out.println("X Value Type: " + cvTypes.get(pnt.getXValueType()));
System.out.println("Y Value Type: " + cvTypes.get(pnt.getYValueType()));
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the sample Excel file
Workbook wb = new Workbook("sampleHandleAutomaticUnitsOfChartAxisLikeMicrosoftExcel.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access first chart
Chart ch = ws.getCharts().get(0);
//Render chart to pdf
ch.toPdf("outputHandleAutomaticUnitsOfChartAxisLikeMicrosoftExcel.pdf");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the Excel file containing chart
Workbook wb = new Workbook("sampleReadAxisLabelsAfterCalculatingTheChart.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access the chart
Chart ch = ws.getCharts().get(0);
//Calculate the chart
ch.calculate();
//Read axis labels of category axis
ArrayList lstLabels = ch.getCategoryAxis().getAxisLabels();
//Print axis labels on console
System.out.println("Category Axis Labels: ");
System.out.println("---------------------");
//Iterate axis labels and print them one by one
for(int i=0; i<lstLabels.size(); i++)
{
System.out.println(lstLabels.get(i));
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load source Excel file
Workbook wb = new Workbook("sampleSetShapeTypeOfDataLabelsOfChart.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access first chart
Chart ch = ws.getCharts().get(0);
//Access first series
Series srs = ch.getNSeries().get(0);
//Set the shape type of data labels i.e. Speech Bubble Oval
srs.getDataLabels().setShapeType(DataLabelShapeType.WEDGE_ELLIPSE_CALLOUT);
//Save the output Excel file
wb.save("outputSetShapeTypeOfDataLabelsOfChart.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load sample Excel file containing cells with formatting.
Workbook wb = new Workbook(srcDir + "sampleChangeCellsAlignmentAndKeepExistingFormatting.xlsx");
// Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
// Create cells range.
Range rng = ws.getCells().createRange("B2:D7");
// Create style object.
Style st = wb.createStyle();
// Set the horizontal and vertical alignment to center.
st.setHorizontalAlignment(TextAlignmentType.CENTER);
st.setVerticalAlignment(TextAlignmentType.CENTER);
// Create style flag object.
StyleFlag flag = new StyleFlag();
// Set style flag alignments true. It is most crucial statement.
// Because if it will be false, no changes will take place.
flag.setAlignments(true);
// Apply style to range of cells.
rng.applyStyle(st, flag);
// Save the workbook in XLSX format.
wb.save(outDir + "outputChangeCellsAlignmentAndKeepExistingFormatting.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Create empty workbook.
Workbook wb = new Workbook();
// Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
// Create range A1:B3.
System.out.println("Creating Range A1:B3\n");
Range rng = ws.getCells().createRange("A1:B3");
// Print range address and cell count.
System.out.println("Range Address: " + rng.getAddress());
System.out.println("Cell Count: " + rng.getCellCount());
// Formatting console output.
System.out.println("----------------------");
System.out.println("");
// Create range A1.
System.out.println("Creating Range A1\n");
rng = ws.getCells().createRange("A1");
// Print range offset, entire column and entire row.
System.out.println("Offset: " + rng.getOffset(2, 2).getAddress());
System.out.println("Entire Column: " + rng.getEntireColumn().getAddress());
System.out.println("Entire Row: " + rng.getEntireRow().getAddress());
// Formatting console output.
System.out.println("----------------------");
System.out.println("");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the sample Excel file
Workbook wb = new Workbook(srcDir + "sampleGetAllHiddenRowsIndicesAfterRefreshingAutoFilter.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Apply autofilter
ws.getAutoFilter().addFilter(0, "Orange");
//True means, it will refresh autofilter and return hidden rows.
//False means, it will not refresh autofilter but return same hidden rows.
int[] rowIndices = ws.getAutoFilter().refresh(true);
System.out.println("Printing Rows Indices, Cell Names and Values Hidden By AutoFilter.");
System.out.println("--------------------------");
for(int i=0; i<rowIndices.length; i++)
{
int r = rowIndices[i];
Cell cell = ws.getCells().get(r, 0);
System.out.println(r + "\t" + cell.getName() + "\t" + cell.getStringValue());
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Create workbook
Workbook wb = new Workbook();
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access cell A1
Cell cell = ws.getCells().get("A1");
//Put some text in cell, it does not have Single Quote at the beginning
cell.putValue("Text");
//Access style of cell A1
Style st = cell.getStyle();
//Print the value of Style.QuotePrefix of cell A1
System.out.println("Quote Prefix of Cell A1: " + st.getQuotePrefix());
//Put some text in cell, it has Single Quote at the beginning
cell.putValue("'Text");
//Access style of cell A1
st = cell.getStyle();
//Print the value of Style.QuotePrefix of cell A1
System.out.println("Quote Prefix of Cell A1: " + st.getQuotePrefix());
//Print information about StyleFlag.QuotePrefix property
System.out.println();
System.out.println("When StyleFlag.QuotePrefix is False, it means, do not update the value of Cell.Style.QuotePrefix.");
System.out.println("Similarly, when StyleFlag.QuotePrefix is True, it means, update the value of Cell.Style.QuotePrefix.");
System.out.println();
//Create an empty style
st = wb.createStyle();
//Create style flag - set StyleFlag.QuotePrefix as false
//It means, we do not want to update the Style.QuotePrefix property of cell A1's style.
StyleFlag flag = new StyleFlag();
flag.setQuotePrefix(false);
//Create a range consisting of single cell A1
Range rng = ws.getCells().createRange("A1");
//Apply the style to the range
rng.applyStyle(st, flag);
//Access the style of cell A1
st = cell.getStyle();
//Print the value of Style.QuotePrefix of cell A1
//It will print True, because we have not updated the Style.QuotePrefix property of cell A1's style.
System.out.println("Quote Prefix of Cell A1: " + st.getQuotePrefix());
//Create an empty style
st = wb.createStyle();
//Create style flag - set StyleFlag.QuotePrefix as true
//It means, we want to update the Style.QuotePrefix property of cell A1's style.
flag = new StyleFlag();
flag.setQuotePrefix(true);
//Apply the style to the range
rng.applyStyle(st, flag);
//Access the style of cell A1
st = cell.getStyle();
//Print the value of Style.QuotePrefix of cell A1
//It will print False, because we have updated the Style.QuotePrefix property of cell A1's style.
System.out.println("Quote Prefix of Cell A1: " + st.getQuotePrefix());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
import java.util.ArrayList;
import com.aspose.cells.*;
import AsposeCellsExamples.Utils;
public class SpecifyFormulaFieldsWhileImportingDataToWorksheet {
static String outDir = Utils.Get_OutputDirectory();
//User-defined class to hold data items
public class DataItems
{
private int m_Number1;
private int m_Number2;
private String m_Formula1;
private String m_Formula2;
public DataItems(int num1, int num2, String form1, String form2)
{
this.m_Number1 = num1;
this.m_Number2 = num2;
this.m_Formula1 = form1;
this.m_Formula2 = form2;
}
public int getNumber1()
{
return this.m_Number1;
}
public int getNumber2()
{
return this.m_Number2;
}
public String getFormula1()
{
return this.m_Formula1;
}
public String getFormula2()
{
return this.m_Formula2;
}
}//DataItems
public void Run() throws Exception
{
System.out.println("Aspose.Cells for Java Version: " + CellsHelper.getVersion());
//List to hold data items
ArrayList<DataItems> dis = new ArrayList<DataItems>();
//Define 1st data item and add it in list
int num1 = 2002;
int num2 = 3502;
String form1 = "=SUM(A2,B2)";
String form2 = "=HYPERLINK(\"https://www.aspose.com\",\"Aspose Website\")";
DataItems di = new DataItems(num1, num2, form1, form2);
dis.add(di);
//Define 2nd data item and add it in list
num1 = 2003;
num2 = 3503;
form1 = "=SUM(A3,B3)";
form2 = "=HYPERLINK(\"https://www.aspose.com\",\"Aspose Website\")";
di = new DataItems(num1, num2, form1, form2);
dis.add(di);
//Define 3rd data item and add it in list
num1 = 2004;
num2 = 3504;
form1 = "=SUM(A4,B4)";
form2 = "=HYPERLINK(\"https://www.aspose.com\",\"Aspose Website\")";
di = new DataItems(num1, num2, form1, form2);
dis.add(di);
//Define 4th data item and add it in list
num1 = 2005;
num2 = 3505;
form1 = "=SUM(A5,B5)";
form2 = "=HYPERLINK(\"https://www.aspose.com\",\"Aspose Website\")";
di = new DataItems(num1, num2, form1, form2);
dis.add(di);
//Create workbook object
Workbook wb = new Workbook();
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Specify import table options
ImportTableOptions opts = new ImportTableOptions();
//Specify which field is formula field, here the last two fields are formula fields
//opts.setColumnIndexes(new int[] {3, 0, 2, 1});
opts.setFormulas(new boolean[] {false, false, true, true });
//Import custom objects
ws.getCells().importCustomObjects(dis, 0, 0, opts);
//Calculate formula
wb.calculateFormula();
//Autofit columns
ws.autoFitColumns();
//Save the output Excel file
wb.save(outDir + "outputSpecifyFormulaFieldsWhileImportingDataToWorksheet.xlsx");
// Print the message
System.out.println("SpecifyFormulaFieldsWhileImportingDataToWorksheet executed successfully.");
}
public static void main(String[] args) throws Exception {
new SpecifyFormulaFieldsWhileImportingDataToWorksheet().Run();
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Create workbook object.
Workbook wb = new Workbook();
//Access built-in document property collection.
BuiltInDocumentPropertyCollection bdpc = wb.getBuiltInDocumentProperties();
//Set the language of the Excel file.
bdpc.setLanguage("German, French");
//Save the workbook in xlsx format.
wb.save(outDir + "outputSpecifyLanguageOfExcelFileUsingBuiltInDocumentProperties.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the sample Excel file
Workbook wb = new Workbook("sampleAccessAndModifyLabelOfOleObject.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access first Ole Object
OleObject oleObject = ws.getOleObjects().get(0);
//Display the Label of the Ole Object
System.out.println("Ole Object Label - Before: " + oleObject.getLabel());
//Modify the Label of the Ole Object
oleObject.setLabel("Aspose APIs");
//Save workbook to byte array output stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
wb.save(baos, SaveFormat.XLSX);
//Convert output to input stream
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
//Set the workbook reference to null
wb = null;
//Load workbook from byte array input stream
wb = new Workbook(bais);
//Access first worksheet
ws = wb.getWorksheets().get(0);
//Access first Ole Object
oleObject = ws.getOleObjects().get(0);
//Display the Label of the Ole Object that has been modified earlier
System.out.println("Ole Object Label - After: " + oleObject.getLabel());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load sample Excel file containing gear type smart art shape.
Workbook wb = new Workbook(srcDir + "sampleExtractTextFromGearTypeSmartArtShape.xlsx");
// Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
// Access first shape.
Shape sh = ws.getShapes().get(0);
// Get the result of gear type smart art shape in the form of group shape.
GroupShape gs = sh.getResultOfSmartArt();
// Get the list of individual shapes consisting of group shape.
Shape[] shps = gs.getGroupedShapes();
// Extract the text of gear type shapes and print them on console.
for (int i = 0; i < shps.length; i++)
{
Shape s = shps[i];
if (s.getType() == AutoShapeType.GEAR_9 || s.getType() == AutoShapeType.GEAR_6)
{
System.out.println("Gear Type Shape Text: " + s.getText());
}
}//for
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load sample Excel file.
Workbook wb = new Workbook(srcDir + "sampleRotateTextWithShapeInsideWorksheet.xlsx");
//Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
//Access cell B4 and add message inside it.
Cell b4 = ws.getCells().get("B4");
b4.putValue("Text is not rotating with shape because RotateTextWithShape is false.");
//Access first shape.
Shape sh = ws.getShapes().get(0);
//Access shape text alignment.
ShapeTextAlignment shapeTextAlignment = sh.getTextBody().getTextAlignment();
//Do not rotate text with shape by setting RotateTextWithShape as false.
shapeTextAlignment.setRotateTextWithShape(false);
//Save the output Excel file.
wb.save(outDir + "outputRotateTextWithShapeInsideWorksheet.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the sample Excel file
Workbook wb = new Workbook("sampleSetMarginsOfCommentOrShapeInsideTheWorksheet.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
for(int idx =0; idx<ws.getShapes().getCount(); idx++)
{
//Access the shape
Shape sh = ws.getShapes().get(idx);
//Access the text alignment
ShapeTextAlignment txtAlign = sh.getTextBody().getTextAlignment();
//Set auto margin false
txtAlign.setAutoMargin(false);
//Set the top, left, bottom and right margins
txtAlign.setTopMarginPt(10);
txtAlign.setLeftMarginPt(10);
txtAlign.setBottomMarginPt(10);
txtAlign.setRightMarginPt(10);
}
//Save the output Excel file
wb.save("outputSetMarginsOfCommentOrShapeInsideTheWorksheet.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Create empty workbook.
Workbook wb = new Workbook();
// Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
// Add textbox inside the worksheet.
int idx = ws.getTextBoxes().add(5, 5, 50, 200);
TextBox tb = ws.getTextBoxes().get(idx);
// Set the text of the textbox.
tb.setText("こんにちは世界");
// Specify the Far East and Latin name of the font.
tb.getTextOptions().setLatinName("Comic Sans MS");
tb.getTextOptions().setFarEastName("KaiTi");
// Save the output Excel file.
wb.save("outputSpecifyFarEastAndLatinNameOfFontInTextOptionsOfShape.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the source Excel file
Workbook wb = new Workbook("sampleSeries_ValuesFormatCode.xlsx");
//Access first worksheet
Worksheet worksheet = wb.getWorksheets().get(0);
//Access first chart
Chart ch = worksheet.getCharts().get(0);
//Add series using an array of values
ch.getNSeries().add("{10000, 20000, 30000, 40000}", true);
//Access the series and set its values format code
Series srs = ch.getNSeries().get(0);
srs.setValuesFormatCode("$#,##0");
//Save the output Excel file
wb.save("outputSeries_ValuesFormatCode.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load your source workbook
Workbook wb = new Workbook(srcDir + "sampleAdvancedFilter.xlsx");
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Apply advanced filter on range A5:D19 and criteria range is A1:D2
// Besides, we want to filter in place
// And, we want all filtered records not just unique records
ws.advancedFilter(true, "A5:D19", "A1:D2", "", false);
// Save the workbook in xlsx format
wb.save(outDir + "outputAdvancedFilter.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Create Connection object - connect to Microsoft Access Students Database
java.sql.Connection conn = java.sql.DriverManager.getConnection("jdbc:ucanaccess://" + srcDir + "Students.accdb");
// Create SQL Statement with Connection object
java.sql.Statement st = conn.createStatement();
// Execute SQL Query and obtain ResultSet
java.sql.ResultSet rs = st.executeQuery("SELECT * FROM Student");
// Create workbook object
Workbook wb = new Workbook();
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Access cells collection
Cells cells = ws.getCells();
// Create import table options
ImportTableOptions options = new ImportTableOptions();
// Import Result Set at (row=2, column=2)
cells.importResultSet(rs, 2, 2, options);
// Execute SQL Query and obtain ResultSet again
rs = st.executeQuery("SELECT * FROM Student");
// Import Result Set at cell G10
cells.importResultSet(rs, "G10", options);
// Autofit columns
ws.autoFitColumns();
// Save the workbook
wb.save(outDir + "outputImportResultSet.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class ShiftFirstRowDownWhenInsertingCellsDataTableRows {
class CellsDataTable implements ICellsDataTable
{
//This is the current row index
int m_index=-1;
//These are your column names
String[] colsNames = new String[] { "Pet", "Fruit", "Country", "Color" };
//These are the data of each column
String[] col0data = new String[] { "Dog", "Cat", "Duck" };
String[] col1data = new String[] { "Apple", "Pear", "Banana" };
String[] col2data = new String[] { "UK", "USA", "China" };
String[] col3data = new String[] { "Red", "Green", "Blue" };
//Combine all of the data into a single two dimensional array
String[][] colsData = new String[][]{ col0data, col1data, col2data, col3data};
public void beforeFirst() {
m_index = -1;
}
public Object get(int columnIndex) {
Object o = null;
o = colsData[columnIndex][m_index];
return o;
}
public Object get(String columnName) {
return null;
}
public String[] getColumns() {
return colsNames;
}
public int getCount() {
return col0data.length;
}
public boolean next() {
m_index++;
return true;
}
}//End Class - CellsDataTable
public void Run() throws Exception
{
String srcDir = Utils.Get_SourceDirectory();
String outDir = Utils.Get_OutputDirectory();
//Create the instance of Cells Data Table
CellsDataTable cellsDataTable = new CellsDataTable();
//Load the sample workbook
Workbook wb = new Workbook(srcDir + "sampleImportTableOptionsShiftFirstRowDown.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Import data table options
ImportTableOptions opts = new ImportTableOptions();
//We do now want to shift the first row down when inserting rows.
opts.setShiftFirstRowDown(false);
//Import cells data table
ws.getCells().importData(cellsDataTable, 2, 2, opts);
//Save the workbook
wb.save(outDir + "outputImportTableOptionsShiftFirstRowDown-False.xlsx");
}
public static void main(String[] args) throws Exception {
ShiftFirstRowDownWhenInsertingCellsDataTableRows pg = new ShiftFirstRowDownWhenInsertingCellsDataTableRows();
pg.Run();
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the source Excel file
Workbook wb = new Workbook(srcDir + "sampleSortData_CustomSortList.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Specify cell area - sort from A1 to A40
CellArea ca = CellArea.createCellArea("A1", "A40");
//Create Custom Sort list
String[] customSortList = new String[] { "USA,US", "Brazil,BR", "China,CN", "Russia,RU", "Canada,CA" };
//Add Key for Column A, Sort it in Ascending Order with Custom Sort List
wb.getDataSorter().addKey(0, SortOrder.ASCENDING, customSortList);
wb.getDataSorter().sort(ws.getCells(), ca);
//Save the output Excel file
wb.save(outDir + "outputSortData_CustomSortList.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the sample smart art shape - Excel file
Workbook wb = new Workbook("sampleSmartArtShape_GetResultOfSmartArt.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access first shape
Shape sh = ws.getShapes().get(0);
//Determine if shape is smart art
System.out.println("Is Smart Art Shape: " + sh.isSmartArt());
//Determine if shape is group shape
System.out.println("Is Group Shape: " + sh.isGroup());
//Convert smart art shape into group shape
System.out.println("Is Group Shape: " + sh.getResultOfSmartArt().isGroup());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the sample smart art shape - Excel file
Workbook wb = new Workbook("sampleSmartArtShape.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access first shape
Shape sh = ws.getShapes().get(0);
//Determine if shape is smart art
System.out.println("Is Smart Art Shape: " + sh.isSmartArt());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load source Excel file
Workbook wb = new Workbook(srcDir + "sampleToFrontOrBack.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access first and fourth shape
Shape sh1 = ws.getShapes().get(0);
Shape sh4 = ws.getShapes().get(3);
//Print the Z-Order position of the shape
System.out.println("Z-Order Shape 1: " + sh1.getZOrderPosition());
//Send this shape to front
sh1.toFrontOrBack(2);
//Print the Z-Order position of the shape
System.out.println("Z-Order Shape 4: " + sh4.getZOrderPosition());
//Send this shape to back
sh4.toFrontOrBack(-2);
//Save the output Excel file
wb.save(outDir + "outputToFrontOrBack.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load sample Excel file
Workbook wb = new Workbook(srcDir + "sampleTextureFill_IsTiling.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access first shape inside the worksheet
Shape sh = ws.getShapes().get(0);
//Tile Picture as a Texture inside the Shape
sh.getFill().getTextureFill().setTiling(true);
//Save the output Excel file
wb.save(outDir + "outputTextureFill_IsTiling.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Open an Excel file.
Workbook workbook = new Workbook(srcDir + "sampleSetDefaultFontPropertyOfPdfSaveOptionsAndImageOrPrintOptions.xlsx");
// Rendering to PNG file format while setting the
// CheckWorkbookDefaultFont attribue to false.
// So, "Times New Roman" font would be used for any missing (not
// installed) font in the workbook.
ImageOrPrintOptions imgOpt = new ImageOrPrintOptions();
imgOpt.setImageFormat(ImageFormat.getPng());
imgOpt.setCheckWorkbookDefaultFont(false);
imgOpt.setDefaultFont("Times New Roman");
SheetRender sr = new SheetRender(workbook.getWorksheets().get(0), imgOpt);
sr.toImage(0, outDir + "outputSetDefaultFontProperty_ImagePNG.png");
// Rendering to TIFF file format while setting the
// CheckWorkbookDefaultFont attribue to false.
// So, "Times New Roman" font would be used for any missing (not
// installed) font in the workbook.
imgOpt.setImageFormat(ImageFormat.getTiff());
WorkbookRender wr = new WorkbookRender(workbook, imgOpt);
wr.toImage(outDir + "outputSetDefaultFontProperty_ImageTIFF.tiff");
// Rendering to PDF file format while setting the
// CheckWorkbookDefaultFont attribue to false.
// So, "Times New Roman" font would be used for any missing (not
// installed) font in the workbook.
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.setDefaultFont("Times New Roman");
saveOptions.setCheckWorkbookDefaultFont(false);
workbook.save(outDir + "outputSetDefaultFontProperty_PDF.pdf", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Implement calculation monitor class
class clsCalculationMonitor extends AbstractCalculationMonitor
{
public void beforeCalculate(int sheetIndex, int rowIndex, int colIndex)
{
//Find the cell name
String cellName = CellsHelper.cellIndexToName(rowIndex, colIndex);
//Print the sheet, row and column index as well as cell name
System.out.println(sheetIndex + "----" + rowIndex + "----" + colIndex + "----" + cellName);
//If cell name is B8, interrupt/cancel the formula calculation
if (cellName.equals("B8") == true)
{
this.interrupt("Interrupt/Cancel the formula calculation");
}//if
}//beforeCalculate
}//clsCalculationMonitor
//---------------------------------------------------------
//---------------------------------------------------------
public void Run() throws Exception
{
//Load the sample Excel file
Workbook wb = new Workbook(srcDir + "sampleCalculationMonitor.xlsx");
//Create calculation options and assign instance of calculation monitor class
CalculationOptions opts = new CalculationOptions();
opts.setCalculationMonitor(new clsCalculationMonitor());
//Calculate formula with calculation options
wb.calculateFormula(opts);
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Create workbook object
Workbook wb = new Workbook();
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access cell B5 and add some message inside it
Cell cell = ws.getCells().get("B5");
cell.putValue("This PDF format is compatible with PDFA-1a.");
//Create pdf save options and set its compliance to PDFA-1a
PdfSaveOptions opts = new PdfSaveOptions();
opts.setCompliance(PdfCompliance.PDF_A_1_A);
//Save the output pdf
wb.save(dataDir + "outputCompliancePdfA1a.pdf", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load sample workbook
Workbook wb = new Workbook(srcDir + "sampleDisableDownlevelRevealedComments.xlsx");
// Disable DisableDownlevelRevealedComments
HtmlSaveOptions opts = new HtmlSaveOptions();
opts.setDisableDownlevelRevealedComments(true);
// Save the workbook in html
wb.save(outDir + "outputDisableDownlevelRevealedComments_true.html", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load sample Excel file
Workbook wb = new Workbook(srcDir + "sampleExportCommentsHTML.xlsx");
// Export comments - set IsExportComments property to true
HtmlSaveOptions opts = new HtmlSaveOptions();
opts.setExportComments(true);
// Save the Excel file to HTML
wb.save(outDir + "outputExportCommentsHTML.html", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Specify load options, we want to load Numbers spreadsheet.
LoadOptions opts = new LoadOptions(LoadFormat.NUMBERS);
// Load the Numbers spreadsheet in workbook with above load options.
Workbook wb = new Workbook(srcDir + "sampleNumbersByAppleInc.numbers", opts);
// Save the workbook to pdf format
wb.save(outDir + "outputNumbersByAppleInc.pdf", SaveFormat.PDF);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Enum to String
String[] strsHtmlCrossStringType = new String[]{"Default", "MSExport", "Cross", "FitToCell"};
//Load the sample Excel file
Workbook wb = new Workbook("sampleHtmlCrossStringType.xlsx");
//Specify HTML Cross Type
HtmlSaveOptions opts = new HtmlSaveOptions();
opts.setHtmlCrossStringType(HtmlCrossType.DEFAULT);
opts.setHtmlCrossStringType(HtmlCrossType.MS_EXPORT);
opts.setHtmlCrossStringType(HtmlCrossType.CROSS);
opts.setHtmlCrossStringType(HtmlCrossType.FIT_TO_CELL);
//Output Html
String strHtmlCrossStringType = strsHtmlCrossStringType[opts.getHtmlCrossStringType()];
wb.save("out" + strHtmlCrossStringType + ".htm", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load source Excel file
Workbook wb = new Workbook(srcDir + "samplePdfBookmarkEntry_DestinationName.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access cell C5
Cell cell = ws.getCells().get("C5");
//Create Bookmark and Destination for this cell
PdfBookmarkEntry bookmarkEntry = new PdfBookmarkEntry();
bookmarkEntry.setText("Text");
bookmarkEntry.setDestination(cell);
bookmarkEntry.setDestinationName("AsposeCells--" + cell.getName());
//Access cell G56
cell = ws.getCells().get("G56");
//Create Sub-Bookmark and Destination for this cell
PdfBookmarkEntry subbookmarkEntry1 = new PdfBookmarkEntry();
subbookmarkEntry1.setText("Text1");
subbookmarkEntry1.setDestination(cell);
subbookmarkEntry1.setDestinationName("AsposeCells--" + cell.getName());
//Access cell L4
cell = ws.getCells().get("L4");
//Create Sub-Bookmark and Destination for this cell
PdfBookmarkEntry subbookmarkEntry2 = new PdfBookmarkEntry();
subbookmarkEntry2.setText("Text2");
subbookmarkEntry2.setDestination(cell);
subbookmarkEntry2.setDestinationName("AsposeCells--" + cell.getName());
//Add Sub-Bookmarks in list
ArrayList list = new ArrayList();
list.add(subbookmarkEntry1);
list.add(subbookmarkEntry2);
//Assign Sub-Bookmarks list to Bookmark Sub-Entry
bookmarkEntry.setSubEntry(list);
//Create PdfSaveOptions and assign Bookmark to it
PdfSaveOptions opts = new PdfSaveOptions();
opts.setBookmark(bookmarkEntry);
//Save the workbook in Pdf format with given pdf save options
wb.save(outDir + "outputPdfBookmarkEntry_DestinationName.pdf", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Implement IStreamProvider
class MyStreamProvider implements IStreamProvider {
public void closeStream(StreamProviderOptions options) throws Exception {
System.out.println("-----Close Stream-----");
}
public void initStream(StreamProviderOptions options) throws Exception {
System.out.println("-----Init Stream-----");
// Read the new image in a memory stream and assign it to Stream property
File imgFile = new File( srcDir + "newPdfSaveOptions_StreamProvider.png");
byte[] bts = new byte[(int) imgFile.length()];
FileInputStream fin = new FileInputStream(imgFile);
fin.read(bts);
fin.close();
ByteArrayOutputStream baout = new ByteArrayOutputStream();
baout.write(bts);
baout.close();
options.setStream(baout);
}
}//MyStreamProvider
// ------------------------------------------------
// ------------------------------------------------
void Run() throws Exception {
// Load source Excel file containing external image
Workbook wb = new Workbook(srcDir + "samplePdfSaveOptions_StreamProvider.xlsx");
// Specify Pdf Save Options - Stream Provider
PdfSaveOptions opts = new PdfSaveOptions();
opts.setOnePagePerSheet(true);
opts.setStreamProvider(new MyStreamProvider());
// Save the workbook to Pdf
wb.save(outDir + "outputPdfSaveOptions_StreamProvider.pdf", opts);
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the Sample Workbook that throws Error on Excel2Pdf conversion
Workbook wb = new Workbook("sampleErrorExcel2Pdf.xlsx");
//Specify Pdf Save Options - Ignore Error
PdfSaveOptions opts = new PdfSaveOptions();
opts.setIgnoreError(true);
//Save the Workbook in Pdf with Pdf Save Options
wb.save("outputErrorExcel2Pdf.pdf", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Create workbook
Workbook wb = new Workbook();
// Access first worksheet - it is empty sheet
Worksheet ws = wb.getWorksheets().get(0);
// Specify image or print options
// Since the sheet is blank, we will set
// OutputBlankPageWhenNothingToPrint to true
// So that empty page gets printed
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setImageFormat(ImageFormat.getPng());
opts.setOutputBlankPageWhenNothingToPrint(true);
// Render empty sheet to png image
SheetRender sr = new SheetRender(ws, opts);
sr.toImage(0, outDir + "OutputBlankPageWhenNothingToPrint.png");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the sample Excel file
Workbook wb = new Workbook("sampleImageOrPrintOptions_PageIndexPageCount.xlsx");
//Access the first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Specify image or print options
//We want to print pages 4, 5, 6, 7
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setPageIndex(3);
opts.setPageCount(4);
opts.setImageFormat(ImageFormat.getPng());
//Create sheet render object
SheetRender sr = new SheetRender(ws, opts);
//Print all the pages as images
for (int i = opts.getPageIndex(); i < sr.getPageCount(); i++)
{
sr.toImage(i, "outputImage-" + (i+1) + ".png");
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Create array of strings that are actually Excel formulas
String str1 = "=\"01-This \" & \"is \" & \"concatenation\"";
String str2 = "=\"02-This \" & \"is \" & \"concatenation\"";
String str3 = "=\"03-This \" & \"is \" & \"concatenation\"";
String str4 = "=\"04-This \" & \"is \" & \"concatenation\"";
String str5 = "=\"05-This \" & \"is \" & \"concatenation\"";
String[] TestFormula = new String[]{str1, str2, str3, str4, str5};
//Create a workbook
Workbook wb = new Workbook();
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Put the smart marker field with formula parameter in cell A1
Cells cells = ws.getCells();
Cell cell = cells.get("A1");
cell.putValue("&=$Test(formula)");
//Create workbook designer, set data source and process it
WorkbookDesigner wd = new WorkbookDesigner(wb);
wd.setDataSource("Test", TestFormula);
wd.process();
//Save the workbook in xlsx format
wb.save(outDir + "outputUsingFormulaParameterInSmartMarkerField.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Certificate file and its password
String certFileName = "AsposeTest.pfx";
String password = "aspose";
// Load the workbook which is already digitally signed to add new digital signature
Workbook workbook = new Workbook(srcDir + "sampleDigitallySignedByCells.xlsx");
// Create the digital signature collection
DigitalSignatureCollection dsCollection = new DigitalSignatureCollection();
// Create new digital signature and add it in digital signature collection
// ------------------------------------------------------------
// --------------Begin::creating signature---------------------
// Load the certificate into an instance of InputStream
InputStream inStream = new FileInputStream(srcDir + certFileName);
// Create an instance of KeyStore with PKCS12 cryptography
java.security.KeyStore inputKeyStore = java.security.KeyStore.getInstance("PKCS12");
// Use the KeyStore.load method to load the certificate stream and its password
inputKeyStore.load(inStream, password.toCharArray());
// Create an instance of DigitalSignature and pass the instance of KeyStore, password, comments and time
DigitalSignature signature = new DigitalSignature(inputKeyStore, password,
"Aspose.Cells added new digital signature in existing digitally signed workbook.",
com.aspose.cells.DateTime.getNow());
dsCollection.add(signature);
// ------------------------------------------------------------
// --------------End::creating signature-----------------------
// Add digital signature collection inside the workbook
workbook.addDigitalSignature(dsCollection);
// Save the workbook and dispose it.
workbook.save(outDir + "outputDigitallySignedByCells.xlsx");
workbook.dispose();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Create Workbook object
Workbook wb = new Workbook();
//Share the Workbook
wb.getSettings().setShared(true);
//Save the Shared Workbook
wb.save("outputSharedWorkbook.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Create empty Excel file
Workbook wb = new Workbook();
//Protect the Shared Workbook with Password
wb.protectSharedWorkbook("1234");
//Uncomment this line to Unprotect the Shared Workbook
//wb.unprotectSharedWorkbook("1234");
//Save the output Excel file
wb.save("outputProtectSharedWorkbook.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load the source Excel Xlsb file
Workbook wb = new Workbook("sampleExternalConnection_XLSB.xlsb");
//Read the first external connection which is actually a DB-Connection
DBConnection dbCon = (DBConnection)wb.getDataConnections().get(0);
//Print the Name, Command and Connection Info of the DB-Connection
System.out.println("Connection Name: " + dbCon.getName());
System.out.println("Command: " + dbCon.getCommand());
System.out.println("Connection Info: " + dbCon.getConnectionInfo());
//Modify the Connection Name
dbCon.setName("NewCust");
//Save the Excel Xlsb file
wb.save("outputExternalConnection_XLSB.xlsb");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class ImplementErrorsAndBooleanValueInRussianOrAnyOtherLanguage {
// Russian Globalization
class RussianGlobalization extends GlobalizationSettings {
public String getErrorValueString(String err) {
switch (err.toUpperCase()) {
case "#NAME?":
return "#RussianName-имя?";
}
return "RussianError-ошибка";
}
public String getBooleanValueString(Boolean bv) {
return bv ? "RussianTrue-правда" : "RussianFalse-ложный";
}
}
public void Run() throws Exception {
System.out.println("Aspose.Cells for Java Version: " + CellsHelper.getVersion());
String srcDir = Utils.Get_SourceDirectory();
String outDir = Utils.Get_OutputDirectory();
// Load the source workbook
Workbook wb = new Workbook(srcDir + "sampleRussianGlobalization.xlsx");
// Set GlobalizationSettings in Russian Language
wb.getSettings().setGlobalizationSettings(new RussianGlobalization());
// Calculate the formula
wb.calculateFormula();
// Save the workbook in pdf format
wb.save(outDir + "outputRussianGlobalization.pdf");
}
public static void main(String[] args) throws Exception {
ImplementErrorsAndBooleanValueInRussianOrAnyOtherLanguage impErr = new ImplementErrorsAndBooleanValueInRussianOrAnyOtherLanguage();
impErr.Run();
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Create empty target workbook
Workbook target = new Workbook();
//Load the Excel file containing VBA-Macro Designer User Form
Workbook templateFile = new Workbook(srcDir + "sampleDesignerForm.xlsm");
//Copy all template worksheets to target workboook
int sheetCount = templateFile.getWorksheets().getCount();
for(int idx=0; idx<sheetCount; idx++)
{
Worksheet ws = templateFile.getWorksheets().get(idx);
if (ws.getType() == SheetType.WORKSHEET)
{
Worksheet s = target.getWorksheets().add(ws.getName());
s.copy(ws);
//Put message in cell A2 of the target worksheet
s.getCells().get("A2").putValue("VBA Macro and User Form copied from template to target.");
}
}//for
//-----------------------------------------------
//Copy the VBA-Macro Designer UserForm from Template to Target
int modCount = templateFile.getWorksheets().getCount();
for(int idx=0; idx<modCount; idx++)
{
VbaModule vbaItem = templateFile.getVbaProject().getModules().get(idx);
if (vbaItem.getName().equals("ThisWorkbook"))
{
//Copy ThisWorkbook module code
target.getVbaProject().getModules().get("ThisWorkbook").setCodes(vbaItem.getCodes());
}
else
{
//Copy other modules code and data
System.out.println(vbaItem.getName());
int vbaMod = 0;
Worksheet sheet = target.getWorksheets().getSheetByCodeName(vbaItem.getName());
if (sheet == null)
{
vbaMod = target.getVbaProject().getModules().add(vbaItem.getType(), vbaItem.getName());
}
else
{
vbaMod = target.getVbaProject().getModules().add(sheet);
}
target.getVbaProject().getModules().get(vbaMod).setCodes(vbaItem.getCodes());
if ((vbaItem.getType() == VbaModuleType.DESIGNER))
{
//Get the data of the user form i.e. designer storage
byte[] designerStorage = templateFile.getVbaProject().getModules().getDesignerStorage(vbaItem.getName());
//Add the designer storage to target Vba Project
target.getVbaProject().getModules().addDesignerStorage(vbaItem.getName(), designerStorage);
}
}//else
}//for
//Save the target workbook
target.save(outDir + "outputDesignerForm.xlsm", SaveFormat.XLSM);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Converting integer enums to string enums
HashMap<Integer, String> paperSizeTypes = new HashMap<Integer, String>();
paperSizeTypes.put(PaperSizeType.PAPER_A_3_EXTRA_TRANSVERSE, "PAPER_A_3_EXTRA_TRANSVERSE");
paperSizeTypes.put(PaperSizeType.PAPER_LETTER, "PAPER_LETTER");
//Create workbook
Workbook wb = new Workbook();
//Add two test worksheets
wb.getWorksheets().add("TestSheet1");
wb.getWorksheets().add("TestSheet2");
//Access both worksheets as TestSheet1 and TestSheet2
Worksheet TestSheet1 = wb.getWorksheets().get("TestSheet1");
Worksheet TestSheet2 = wb.getWorksheets().get("TestSheet2");
//Set the Paper Size of TestSheet1 to PaperA3ExtraTransverse
TestSheet1.getPageSetup().setPaperSize(PaperSizeType.PAPER_A_3_EXTRA_TRANSVERSE);
//Print the Paper Size of both worksheets
System.out.println("Before Paper Size: " + paperSizeTypes.get(TestSheet1.getPageSetup().getPaperSize()));
System.out.println("Before Paper Size: " + paperSizeTypes.get(TestSheet2.getPageSetup().getPaperSize()));
System.out.println();
//Copy the PageSetup from TestSheet1 to TestSheet2
TestSheet2.getPageSetup().copy(TestSheet1.getPageSetup(), new CopyOptions());
//Print the Paper Size of both worksheets
System.out.println("After Paper Size: " + paperSizeTypes.get(TestSheet1.getPageSetup().getPaperSize()));
System.out.println("After Paper Size: " + paperSizeTypes.get(TestSheet2.getPageSetup().getPaperSize()));
System.out.println();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load the first workbook having automatic paper size false
Workbook wb1 = new Workbook(srcDir + "samplePageSetupIsAutomaticPaperSize-False.xlsx");
// Load the second workbook having automatic paper size true
Workbook wb2 = new Workbook(srcDir + "samplePageSetupIsAutomaticPaperSize-True.xlsx");
// Access first worksheet of both workbooks
Worksheet ws11 = wb1.getWorksheets().get(0);
Worksheet ws12 = wb2.getWorksheets().get(0);
// Print the PageSetup.IsAutomaticPaperSize property of both worksheets
System.out.println("First Worksheet of First Workbook - IsAutomaticPaperSize: " + ws11.getPageSetup().isAutomaticPaperSize());
System.out.println("First Worksheet of Second Workbook - IsAutomaticPaperSize: " + ws12.getPageSetup().isAutomaticPaperSize());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Create workbook object
Workbook wb = new Workbook();
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Set custom paper size in unit of inches
ws.getPageSetup().customPaperSize(6, 4);
//Access cell B4
Cell b4 = ws.getCells().get("B4");
//Add the message in cell B4
b4.putValue("Pdf Page Dimensions: 6.00 x 4.00 in");
//Save the workbook in pdf format
wb.save(outDir + "outputCustomPaperSize.pdf");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load source Excel file
Workbook wb = new Workbook(srcDir + "sampleRemoveExistingPrinterSettingsOfWorksheets.xlsx");
//Get the sheet counts of the workbook
int sheetCount = wb.getWorksheets().getCount();
//Iterate all sheets
for(int i=0; i<sheetCount; i++)
{
//Access the i-th worksheet
Worksheet ws = wb.getWorksheets().get(i);
//Access worksheet page setup
PageSetup ps = ws.getPageSetup();
//Check if printer settings for this worksheet exist
if(ps.getPrinterSettings() != null)
{
//Print the following message
System.out.println("PrinterSettings of this worksheet exist.");
//Print sheet name and its paper size
System.out.println("Sheet Name: " + ws.getName());
System.out.println("Paper Size: " + ps.getPaperSize());
//Remove the printer settings by setting them null
ps.setPrinterSettings(null);
System.out.println("Printer settings of this worksheet are now removed by setting it null.");
System.out.println("");
}//if
}//for
//Save the workbook
wb.save(outDir + "outputRemoveExistingPrinterSettingsOfWorksheets.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load source Excel file
Workbook wb = new Workbook("sampleSheetId.xlsx");
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Print its Sheet or Tab Id on console
System.out.println("Sheet or Tab Id: " + ws.getTabId());
//Change Sheet or Tab Id
ws.setTabId(358);
//Save the workbook
wb.save("outputSheetId.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load sample Excel file having Xml Map
Workbook wb = new Workbook("sampleRootElementNameOfXmlMap.xlsx");
//Access first Xml Map inside the Workbook
XmlMap xmap = wb.getWorksheets().getXmlMaps().get(0);
//Print Root Element Name of Xml Map on Console
System.out.println("Root Element Name Of Xml Map: " + xmap.getRootElementName());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load XLSX file containing data from XML file
Workbook workbook = new Workbook("XML Data.xlsx");
// Access the first worksheet
Worksheet ws = workbook.getWorksheets().get(0);
// Access ListObject from the first sheet
ListObject listObject = ws.getListObjects().get(0);
// Get the url of the list object's xml map data binding
String url = listObject.getXmlMap().getDataBinding().getUrl();
// Display XML file name
System.out.println(url);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Load sample Excel file having Xml Map
Workbook wb = new Workbook("sampleXmlMapQuery.xlsx");
//Access first XML Map
XmlMap xmap = wb.getWorksheets().getXmlMaps().get(0);
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Query Xml Map from Path - /MiscData
System.out.println("Query Xml Map from Path - /MiscData");
ArrayList ret = ws.xmlMapQuery("/MiscData", xmap);
//Print returned ArrayList values
for (int i = 0; i < ret.size(); i++)
{
System.out.println(ret.get(i));
}
System.out.println("");
//Query Xml Map from Path - /MiscData/row/Color
System.out.println("Query Xml Map from Path - /MiscData/row/Color");
ret = ws.xmlMapQuery("/MiscData/row/Color", xmap);
//Print returned ArrayList values
for (int i = 0; i < ret.size(); i++)
{
System.out.println(ret.get(i));
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddFormulasandCalculateResults.class);
// Instantiating a Workbook object
Workbook book = new Workbook();
// Obtaining the reference of the newly added worksheet
int sheetIndex = book.getWorksheets().add();
Worksheet worksheet = book.getWorksheets().get(sheetIndex);
Cells cells = worksheet.getCells();
Cell cell = null;
// Adding a value to "A1" cell
cell = cells.get("A1");
cell.setValue(1);
// Adding a value to "A2" cell
cell = cells.get("A2");
cell.setValue(2);
// Adding a value to "A3" cell
cell = cells.get("A3");
cell.setValue(3);
// Adding a SUM formula to "A4" cell
cell = cells.get("A4");
cell.setFormula("=SUM(A1:A3)");
// Calculating the results of formulas
book.calculateFormula();
// Saving the Excel file
book.save(dataDir + "book1.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DynamicFormulas.class);
// Instantiating a WorkbookDesigner object
WorkbookDesigner designer = new WorkbookDesigner();
// Set workbook which containing smart markers
Workbook workbook = new Workbook(dataDir + "designerFile");
designer.setWorkbook(workbook);
// Set the data source for the designer spreadsheet
designer.setDataSource(dataSet);
// Process the smart markers
designer.process();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
import java.util.ArrayList;
import com.aspose.cells.BackgroundType;
import com.aspose.cells.Color;
import com.aspose.cells.Range;
import com.aspose.cells.Style;
import com.aspose.cells.StyleFlag;
import com.aspose.cells.Workbook;
import com.aspose.cells.WorkbookDesigner;
import com.aspose.cells.Worksheet;
public class UsingGenericList {
public static void main(String[] args) throws Exception {
// Create a designer workbook
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.getWorksheets().get(0);
worksheet.getCells().get("A1").putValue("Husband Name");
worksheet.getCells().get("A2").putValue("&=Husband.Name");
worksheet.getCells().get("B1").putValue("Husband Age");
worksheet.getCells().get("B2").putValue("&=Husband.Age");
worksheet.getCells().get("C1").putValue("Wife's Name");
worksheet.getCells().get("C2").putValue("&=Husband.Wives.Name");
worksheet.getCells().get("D1").putValue("Wife's Age");
worksheet.getCells().get("D2").putValue("&=Husband.Wives.Age");
// Apply Style to A1:D1
Range range = worksheet.getCells().createRange("A1:D1");
Style style = workbook.createStyle();
style.getFont().setBold(true);
style.setForegroundColor(Color.getYellow());
style.setPattern(BackgroundType.SOLID);
StyleFlag flag = new StyleFlag();
flag.setAll(true);
range.applyStyle(style, flag);
// Initialize WorkbookDesigner object
WorkbookDesigner designer = new WorkbookDesigner();
// Load the template file
designer.setWorkbook(workbook);
ArrayList<Husband> list = new ArrayList<Husband>();
// Create the relevant Wife objects for the Husband object
ArrayList<Wife> wives = new ArrayList<Wife>();
wives.add(new Wife("Chen Zhao", 34));
wives.add(new Wife("Jamima Winfrey", 28));
wives.add(new Wife("Reham Smith", 35));
// Create a Husband object
Husband h1 = new Husband("Mark John", 30, wives);
// Create the relevant Wife objects for the Husband object
wives = new ArrayList<Wife>();
wives.add(new Wife("Karishma Jathool", 36));
wives.add(new Wife("Angela Rose", 33));
wives.add(new Wife("Hina Khanna", 45));
// Create a Husband object
Husband h2 = new Husband("Masood Shankar", 40, wives);
// Add the objects to the list
list.add(h1);
list.add(h2);
// Specify the DataSource
designer.setDataSource("Husband", list);
// Process the markers
designer.process();
// Autofit columns
worksheet.autoFitColumns();
// Save the Excel file.
designer.getWorkbook().save("output.xlsx");
}
// This is the code for Wife.java class
public class Wife {
private String m_Name;
private int m_Age;
public Wife(String name, int age) {
this.m_Name = name;
this.m_Age = age;
}
public String getName() {
return m_Name;
}
public int getAge() {
return m_Age;
}
}
public class Husband {
private String m_Name;
private int m_Age;
private ArrayList<Wife> m_Wives;
public Husband(String name, int age, ArrayList<Wife> wives) {
this.m_Name = name;
this.m_Age = age;
this.m_Wives = wives;
}
public String getName() {
return m_Name;
}
public int getAge() {
return m_Age;
}
public ArrayList<Wife> getWives() {
return m_Wives;
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(UsingHTMLProperty.class);
Workbook workbook = new Workbook();
WorkbookDesigner designer = new WorkbookDesigner();
designer.setWorkbook(workbook);
workbook.getWorksheets().get(0).getCells().get("A1").putValue("&=$VariableArray(HTML)");
designer.setDataSource("VariableArray",
new String[] { "Hello <b>World</b>", "Arabic", "Hindi", "Urdu", "French" });
designer.process();
workbook.save(dataDir + "dest.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(UsingNestedObjects.class);
Workbook workbook = new Workbook("designer.xlsx");
WorkbookDesigner designer = new WorkbookDesigner();
designer.setWorkbook(workbook);
ArrayList<Individual> list = new ArrayList<Individual>();
list.add(new Individual("John", 23, new Wife("Jill", 20)));
list.add(new Individual("Jack", 25, new Wife("Hilly", 21)));
list.add(new Individual("James", 26, new Wife("Hally", 22)));
list.add(new Individual("Baptist", 27, new Wife("Newly", 23)));
designer.setDataSource("Individual", list);
designer.process(false);
workbook.save("output.xlsx");
}
// This is the code for Individual.java class
public class Individual {
private String m_Name;
private int m_Age;
private Wife m_Wife;
public Individual(String name, int age, Wife wife) {
this.m_Name = name;
this.m_Age = age;
this.m_Wife = wife;
}
public String getName() {
return m_Name;
}
public int getAge() {
return m_Age;
}
public Wife getWife() {
return m_Wife;
}
}
// This is the code for Wife.java class
public class Wife {
private String m_Name;
private int m_Age;
public Wife(String name, int age) {
this.m_Name = name;
this.m_Age = age;
}
public String getName() {
return m_Name;
}
public int getAge() {
return m_Age;
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(UsingVariableArray.class);
// Instantiate a new Workbook designer.
WorkbookDesigner report = new WorkbookDesigner();
// Get the first worksheet of the workbook.
Worksheet w = report.getWorkbook().getWorksheets().get(0);
// Set the Variable Array marker to a cell.
// You may also place this Smart Marker into a template file manually in
// Ms Excel and then open this file via Workbook.
w.getCells().get("A1").putValue("&=$VariableArray");
// Set the DataSource for the marker(s).
report.setDataSource("VariableArray", new String[] { "English", "Arabic", "Hindi", "Urdu", "French" });
// Process the markers.
report.process(false);
// Save the Excel file.
report.getWorkbook().save(dataDir + "out_varaiblearray1.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AccessAndUpdatePortions.class);
Workbook workbook = new Workbook(dataDir + "source.xlsx");
Worksheet worksheet = workbook.getWorksheets().get(0);
Cell cell = worksheet.getCells().get("A1");
System.out.println("Before updating the font settings....");
FontSetting[] fnts = cell.getCharacters();
for (int i = 0; i < fnts.length; i++) {
System.out.println(fnts[i].getFont().getName());
}
// Modify the first FontSetting Font Name
fnts[0].getFont().setName("Arial");
// And update it using SetCharacters() method
cell.setCharacters(fnts);
System.out.println();
System.out.println("After updating the font settings....");
fnts = cell.getCharacters();
for (int i = 0; i < fnts.length; i++) {
System.out.println(fnts[i].getFont().getName());
}
// Save workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AccessingTablefromCell.class);
// Create workbook from source Excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access cell D5 which lies inside the table
Cell cell = worksheet.getCells().get("D5");
// Put value inside the cell D5
cell.putValue("D5 Data");
// Access the Table from this cell
ListObject table = cell.getTable();
// Add some value using Row and Column Offset
table.putCellValue(2, 2, "Offset [2,2]");
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AccessTextBoxName.class);
Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);
int idx = sheet.getTextBoxes().add(10, 10, 10, 10);
// Create a texbox with some text and assign it some name
TextBox tb1 = sheet.getTextBoxes().get(idx);
tb1.setName("MyTextBox");
tb1.setText("This is MyTextBox");
// Access the same textbox via its name
TextBox tb2 = sheet.getTextBoxes().get("MyTextBox");
// Displaying the text of the textbox accessed by its name
System.out.println(tb2.getText());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ActivatingSheetsandActivatingCell.class);
// Instantiate a new Workbook
Workbook workbook = new Workbook();
// Get the first worksheet in the workbook
Worksheet worksheet = workbook.getWorksheets().get(0);
// Get the cells in the worksheet
Cells cells = worksheet.getCells();
// Input data into B2 cell
cells.get(1, 1).putValue("Hello World!");
// Set the first sheet as an active sheet
workbook.getWorksheets().setActiveSheetIndex(0);
// Set B2 cell as an active cell in the worksheet
worksheet.setActiveCell("B2");
// Set the B column as the first visible column in the worksheet
worksheet.setFirstVisibleColumn(1);
// Set the 2nd row as the first visible row in the worksheet
worksheet.setFirstVisibleRow(1);
// Save the excel file
workbook.save(dataDir + "activecell.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddActiveXControl.class);
// Create workbook object
Workbook wb = new Workbook();
// Access first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
// Add Toggle Button ActiveX Control inside the Shape Collection
Shape s = sheet.getShapes().addActiveXControl(ControlType.TOGGLE_BUTTON, 4, 0, 4, 0, 100, 30);
// Access the ActiveX control object and set its linked cell property
ActiveXControl c = s.getActiveXControl();
c.setLinkedCell("A1");
// Save the worbook in xlsx format
wb.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddConditionalIconsSet.class);
// Instantiate an instance of Workbook
Workbook workbook = new Workbook();
// Get the first worksheet (default worksheet) in the workbook
Worksheet worksheet = workbook.getWorksheets().get(0);
// Get the cells
Cells cells = worksheet.getCells();
// Set the columns widths (A, B and C)
worksheet.getCells().setColumnWidth(0, 24);
worksheet.getCells().setColumnWidth(1, 24);
worksheet.getCells().setColumnWidth(2, 24);
// Input date into the cells
cells.get("A1").setValue("KPIs");
cells.get("A2").setValue("Total Turnover (Sales at List)");
cells.get("A3").setValue("Total Gross Margin %");
cells.get("A4").setValue("Total Net Margin %");
cells.get("B1").setValue("UA Contract Size Group 4");
cells.get("B2").setValue(19551794);
cells.get("B3").setValue(11.8070745566204);
cells.get("B4").setValue(11.858589818569);
cells.get("C1").setValue("UA Contract Size Group 3");
cells.get("C2").setValue(8150131.66666667);
cells.get("C3").setValue(10.3168384396244);
cells.get("C4").setValue(11.3326931937091);
// Get the conditional icon's image data
byte[] imagedata = ConditionalFormattingIcon.getIconImageData(IconSetType.TRAFFIC_LIGHTS_31, 0);
// Create a stream based on the image data
ByteArrayInputStream stream = new ByteArrayInputStream(imagedata);
// Add the picture to the cell based on the stream
worksheet.getPictures().add(1, 1, stream);
// Get the conditional icon's image data
byte[] imagedata1 = ConditionalFormattingIcon.getIconImageData(IconSetType.ARROWS_3, 2);
// Create a stream based on the image data
ByteArrayInputStream stream1 = new ByteArrayInputStream(imagedata1);
// Add the picture to the cell based on the stream
worksheet.getPictures().add(1, 2, stream1);
// Get the conditional icon's image data
byte[] imagedata2 = ConditionalFormattingIcon.getIconImageData(IconSetType.SYMBOLS_3, 0);
// Create a stream based on the image data
ByteArrayInputStream stream2 = new ByteArrayInputStream(imagedata2);
// Add the picture to the cell based on the stream
worksheet.getPictures().add(2, 1, stream2);
// Get the conditional icon's image data
byte[] imagedata3 = ConditionalFormattingIcon.getIconImageData(IconSetType.STARS_3, 0);
// Create a stream based on the image data
ByteArrayInputStream stream3 = new ByteArrayInputStream(imagedata3);
// Add the picture to the cell based on the stream
worksheet.getPictures().add(2, 2, stream3);
// Get the conditional icon's image data
byte[] imagedata4 = ConditionalFormattingIcon.getIconImageData(IconSetType.BOXES_5, 1);
// Create a stream based on the image data
ByteArrayInputStream stream4 = new ByteArrayInputStream(imagedata4);
// Add the picture to the cell based on the stream
worksheet.getPictures().add(3, 1, stream4);
// Get the conditional icon's image data
byte[] imagedata5 = ConditionalFormattingIcon.getIconImageData(IconSetType.FLAGS_3, 1);
// Create a stream based on the image data
ByteArrayInputStream stream5 = new ByteArrayInputStream(imagedata5);
// Add the picture to the cell based on the stream
worksheet.getPictures().add(3, 2, stream5);
// Save the Excel file
workbook.save(dataDir + "outfile_cond_icons1.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddCustomLabelsToDataPoints.class);
Workbook workbook = new Workbook(FileFormatType.XLSX);
Worksheet sheet = workbook.getWorksheets().get(0);
// Put data
sheet.getCells().get(0, 0).putValue(1);
sheet.getCells().get(0, 1).putValue(2);
sheet.getCells().get(0, 2).putValue(3);
sheet.getCells().get(1, 0).putValue(4);
sheet.getCells().get(1, 1).putValue(5);
sheet.getCells().get(1, 2).putValue(6);
sheet.getCells().get(2, 0).putValue(7);
sheet.getCells().get(2, 1).putValue(8);
sheet.getCells().get(2, 2).putValue(9);
// Generate the chart
int chartIndex = sheet.getCharts().add(ChartType.SCATTER_CONNECTED_BY_LINES_WITH_DATA_MARKER, 5, 1, 24, 10);
Chart chart = sheet.getCharts().get(chartIndex);
chart.getTitle().setText("Test");
chart.getCategoryAxis().getTitle().setText("X-Axis");
chart.getValueAxis().getTitle().setText("Y-Axis");
chart.getNSeries().setCategoryData("A1:C1");
// Insert series
chart.getNSeries().add("A2:C2", false);
Series series = chart.getNSeries().get(0);
int pointCount = series.getPoints().getCount();
for (int i = 0; i < pointCount; i++) {
ChartPoint pointIndex = series.getPoints().get(i);
pointIndex.getDataLabels().setText("Series 1" + "\n" + "Point " + i);
}
// Insert series
chart.getNSeries().add("A3:C3", false);
series = chart.getNSeries().get(1);
pointCount = series.getPoints().getCount();
for (int i = 0; i < pointCount; i++) {
ChartPoint pointIndex = series.getPoints().get(i);
pointIndex.getDataLabels().setText("Series 2" + "\n" + "Point " + i);
}
workbook.save(dataDir + "Test.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddHTMLRichText.class);
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.getWorksheets().get(0);
Cell cell = worksheet.getCells().get("A1");
cell.setHtmlString(
"<Font Style=\"FONT-WEIGHT: bold;FONT-STYLE: italic;TEXT-DECORATION: underline;FONT-FAMILY: Arial;FONT-SIZE: 11pt;COLOR: #ff0000;\">This is simple HTML formatted text.</Font>");
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(AddingTwoAndThreeColorScale.class);
// Create workbook
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Add some data in cells
worksheet.getCells().get("A1").putValue("2-Color Scale");
worksheet.getCells().get("D1").putValue("3-Color Scale");
for (int i = 2; i <= 15; i++) {
worksheet.getCells().get("A" + i).putValue(i);
worksheet.getCells().get("D" + i).putValue(i);
}
// Adding 2-Color Scale Conditional Formatting
CellArea ca = CellArea.createCellArea("A2", "A15");
int idx = worksheet.getConditionalFormattings().add();
FormatConditionCollection fcc = worksheet.getConditionalFormattings().get(idx);
fcc.addCondition(FormatConditionType.COLOR_SCALE);
fcc.addArea(ca);
FormatCondition fc = worksheet.getConditionalFormattings().get(idx).get(0);
fc.getColorScale().setIs3ColorScale(false);
fc.getColorScale().setMaxColor(Color.getLightBlue());
fc.getColorScale().setMinColor(Color.getLightGreen());
// Adding 3-Color Scale Conditional Formatting
ca = CellArea.createCellArea("D2", "D15");
idx = worksheet.getConditionalFormattings().add();
fcc = worksheet.getConditionalFormattings().get(idx);
fcc.addCondition(FormatConditionType.COLOR_SCALE);
fcc.addArea(ca);
fc = worksheet.getConditionalFormattings().get(idx).get(0);
fc.getColorScale().setIs3ColorScale(true);
fc.getColorScale().setMaxColor(Color.getLightBlue());
fc.getColorScale().setMidColor(Color.getYellow());
fc.getColorScale().setMinColor(Color.getLightGreen());
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddLibraryReference.class);
Workbook workbook = new Workbook();
VbaProject vbaProj = workbook.getVbaProject();
vbaProj.getReferences().addRegisteredReference("stdole",
"*\\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\\Windows\\system32\\stdole2.tlb#OLE Automation");
vbaProj.getReferences().addRegisteredReference("Office",
"*\\G{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}#2.0#0#C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE14\\MSO.DLL#Microsoft Office 14.0 Object Library");
workbook.save(dataDir + "output.xlsm");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(AddLibraryReferenceToVbaProject.class);
String outputPath = dataDir + "Output-1.xlsm";
Workbook workbook = new Workbook();
VbaProject vbaProj = workbook.getVbaProject();
vbaProj.getReferences().addRegisteredReference("stdole", "*\\G{00020430-0000-0000-C000-000000000046}#2.0#0#C:\\Windows\\system32\\stdole2.tlb#OLE Automation");
vbaProj.getReferences().addRegisteredReference("Office", "*\\G{2DF8D04C-5BFA-101B-BDE5-00AA0044DE52}#2.0#0#C:\\Program Files\\Common Files\\Microsoft Shared\\OFFICE14\\MSO.DLL#Microsoft Office 14.0 Object Library");
workbook.save(outputPath);
System.out.println("File saved " + outputPath);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddNamedRangeWithWorkbookScope.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Get Worksheets collection
WorksheetCollection worksheets = workbook.getWorksheets();
// Accessing the first worksheet in the Excel file
Worksheet sheet = worksheets.get(0);
// Get worksheet Cells collection
Cells cells = sheet.getCells();
// Creating a workbook scope named range
Range namedRange = cells.createRange("A1", "C10");
namedRange.setName("workbookScope");
// Saving the modified Excel file in default format
workbook.save(dataDir + "output.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddNamedRangeWithWorkbookScope.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Get Worksheets collection
WorksheetCollection worksheets = workbook.getWorksheets();
// Accessing the first worksheet in the Excel file
Worksheet sheet = worksheets.get(0);
// Get worksheet Cells collection
Cells cells = sheet.getCells();
// Creating a workbook scope named range
Range namedRange = cells.createRange("A1", "C10");
namedRange.setName("Sheet1!local");
// Saving the modified Excel file in default format
workbook.save(dataDir + "output.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddPDFBookmarks.class);
// Instantiate a new workbook.
Workbook workbook = new Workbook();
// Get the worksheets in the workbook.
WorksheetCollection worksheets = workbook.getWorksheets();
// Add a sheet to the workbook.
worksheets.add("1");
// Add 2nd sheet to the workbook.
worksheets.add("2");
// Add the third sheet.
worksheets.add("3");
// Get cells in different worksheets.
Cell cellInPage1 = worksheets.get(0).getCells().get("A1");
Cell cellInPage2 = worksheets.get(1).getCells().get("A1");
Cell cellInPage3 = worksheets.get(2).getCells().get("A1");
// Add a value to the A1 cell in the first sheet.
cellInPage1.setValue("a");
// Add a value to the A1 cell in the second sheet.
cellInPage2.setValue("b");
// Add a value to the A1 cell in the third sheet.
cellInPage3.setValue("c");
// Create the PdfBookmark entry object.
PdfBookmarkEntry pbeRoot = new PdfBookmarkEntry();
// Set its text.
pbeRoot.setText("root");
// Set its destination source page.
pbeRoot.setDestination(cellInPage1);
// Set the bookmark collapsed.
pbeRoot.setOpen(false);
// Add a new PdfBookmark entry object.
PdfBookmarkEntry subPbe1 = new PdfBookmarkEntry();
// Set its text.
subPbe1.setText("1");
// Set its destination source page.
subPbe1.setDestination(cellInPage2);
// Add another PdfBookmark entry object.
PdfBookmarkEntry subPbe2 = new PdfBookmarkEntry();
// Set its text.
subPbe2.setText("2");
// Set its destination source page.
subPbe2.setDestination(cellInPage3);
// Create an array list.
ArrayList subEntryList = new ArrayList();
// Add the entry objects to it.
subEntryList.add(subPbe1);
subEntryList.add(subPbe2);
pbeRoot.setSubEntry(subEntryList);
// Set the PDF bookmarks.
PdfSaveOptions options = new PdfSaveOptions();
options.setBookmark(pbeRoot);
// Save the PDF file.
workbook.save(dataDir, options);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(AddPicturetoExcelComment.class) + "articles/";
// Instantiate a Workbook
Workbook workbook = new Workbook();
// Get a reference of comments collection with the first sheet
CommentCollection comments = workbook.getWorksheets().get(0).getComments();
// Add a comment to cell A1
int commentIndex = comments.add(0, 0);
Comment comment = comments.get(commentIndex);
comment.setNote("First note.");
comment.getFont().setName("Times New Roman");
// Load/Read an image into stream
String logo_url = dataDir + "school.jpg";
// Creating the instance of the FileInputStream object to open the logo/picture in the stream
FileInputStream inFile = new FileInputStream(logo_url);
// Setting the logo/picture
byte[] picData = new byte[inFile.available()];
inFile.read(picData);
// Set image data to the shape associated with the comment
comment.getCommentShape().getFill().setImageData(picData);
// Save the workbook
workbook.save(dataDir + "APToExcelComment_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AddVBAModuleAndCode.class);
// Create new workbook
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Add VBA Module
int idx = workbook.getVbaProject().getModules().add(worksheet);
// Access the VBA Module, set its name and codes
VbaModule module = workbook.getVbaProject().getModules().get(idx);
module.setName("TestModule");
module.setCodes("Sub ShowMessage()" + "\r\n" + " MsgBox \"Welcome to Aspose!\"" + "\r\n" + "End Sub");
// Save the workbook
workbook.save(dataDir + "output.xlsm", SaveFormat.XLSM);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(AddWordArtText.class) + "articles/";
// Create workbook object
Workbook wb = new Workbook();
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Add Word Art Text with Built-in Styles
ws.getShapes().addWordArt(PresetWordArtStyle.WORD_ART_STYLE_1, "Aspose File Format APIs", 00, 0, 0, 0, 100, 800);
ws.getShapes().addWordArt(PresetWordArtStyle.WORD_ART_STYLE_2, "Aspose File Format APIs", 10, 0, 0, 0, 100, 800);
ws.getShapes().addWordArt(PresetWordArtStyle.WORD_ART_STYLE_3, "Aspose File Format APIs", 20, 0, 0, 0, 100, 800);
ws.getShapes().addWordArt(PresetWordArtStyle.WORD_ART_STYLE_4, "Aspose File Format APIs", 30, 0, 0, 0, 100, 800);
ws.getShapes().addWordArt(PresetWordArtStyle.WORD_ART_STYLE_5, "Aspose File Format APIs", 40, 0, 0, 0, 100, 800);
// Save the workbook in xlsx format
wb.save(dataDir + "AddWordArtText_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(AddWordArtWatermarkToChart.class) + "articles/";
// Instantiate a new workbook, Open the existing excel file.
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
// Get the chart in the first worksheet.
Chart chart = workbook.getWorksheets().get(0).getCharts().get(0);
// Add a WordArt watermark (shape) to the chart's plot area.
Shape wordart = chart.getShapes().addTextEffectInChart(MsoPresetTextEffect.TEXT_EFFECT_1, "CONFIDENTIAL",
"Arial Black", 66, false, false, 1200, 500, 2000, 3000);
// Get the shape's fill format.
FillFormat wordArtFormat = wordart.getFill();
// Set the transparency.
wordArtFormat.setTransparency(0.9);
// Get the line format.
LineFormat lineFormat = wordart.getLine();
// Set Line format to invisible.
lineFormat.setWeight(0.0);
// Save the excel file.
workbook.save(dataDir + "AWArtWToC_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(AddWordArtWatermarkToWorksheet.class) + "articles/";
// Instantiate a new Workbook
Workbook workbook = new Workbook();
// Get the first default sheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Add Watermark
Shape wordart = sheet.getShapes().addTextEffect(MsoPresetTextEffect.TEXT_EFFECT_1, "CONFIDENTIAL",
"Arial Black", 50, false, true, 18, 8, 1, 1, 130, 800);
// Get the fill format of the word art
FillFormat wordArtFormat = wordart.getFill();
// Set the color
wordArtFormat.setOneColorGradient(Color.getRed(), 0.2, GradientStyleType.HORIZONTAL, 2);
// Set the transparency
wordArtFormat.setTransparency(0.9);
// Make the line invisible
LineFormat lineFormat = wordart.getLine();
lineFormat.setWeight(0.0);
// Save the file
workbook.save(dataDir + "AWArtWToWorksheet_out.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(AddXMLMapInsideWorkbook.class) + "articles/";
// Create workbook object
Workbook wb = new Workbook();
// Add xml map found inside the sample.xml inside the workbook
wb.getWorksheets().getXmlMaps().add(dataDir + "sample.xml");
// Save the workbook in xlsx format
wb.save(dataDir + "AddXMLMapInsideWorkbook_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ApplyingEncryption.class);
// Instantiate a Workbook object.
Workbook workbook = new Workbook(dataDir + "Book1.xls");
// Password protect the file.
workbook.getSettings().setPassword("1234");
// Specify Strong Encryption type (RC4,Microsoft Strong Cryptographic Provider).
workbook.setEncryptionOptions(EncryptionType.STRONG_CRYPTOGRAPHIC_PROVIDER, 128);
// Save the Excel file.
workbook.save(dataDir + "encryptedBook1.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ApplyingSubscript.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Accessing the added worksheet in the Excel file
Worksheet worksheet = workbook.getWorksheets().get(0);
Cells cells = worksheet.getCells();
// Adding some value to the "A1" cell
Cell cell = cells.get("A1");
cell.setValue("Hello");
// Setting the font name to "Times New Roman"
Style style = cell.getStyle();
Font font = style.getFont();
font.setSubscript(true);
cell.setStyle(style);
// Saving the modified Excel file in default format
workbook.save(dataDir + "Subscript.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ApplyingSubtotal.class);
// Create workbook from source Excel file
Workbook workbook = new Workbook(dataDir + "Book1.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Get the Cells collection in the first worksheet
Cells cells = worksheet.getCells();
// Create a cellarea i.e.., A2:B11
CellArea ca = CellArea.createCellArea("A2", "B11");
// Apply subtotal, the consolidation function is Sum and it will applied to
// Second column (B) in the list
cells.subtotal(ca, 0, ConsolidationFunction.SUM, new int[] { 1 }, true, false, true);
// Set the direction of outline summary
worksheet.getOutline().SummaryRowBelow = true;
// Save the excel file
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ApplyingSuperscript.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Accessing the added worksheet in the Excel file
Worksheet worksheet = workbook.getWorksheets().get(0);
Cells cells = worksheet.getCells();
// Adding some value to the "A1" cell
Cell cell = cells.get("A1");
cell.setValue("Hello");
// Setting the font name to "Times New Roman"
Style style = cell.getStyle();
Font font = style.getFont();
font.setSuperscript(true);
cell.setStyle(style);
// Saving the modified Excel file in default format
workbook.save(dataDir + "Superscript.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ApplyShadingToAlternateRowsAndColumns.class);
/*
* Create an instance of Workbook Optionally load an existing spreadsheet by passing its stream or path to Workbook
* constructor
*/
Workbook book = new Workbook();
// Access the Worksheet on which desired rule has to be applied
Worksheet sheet = book.getWorksheets().get(0);
// Add FormatConditions to the instance of Worksheet
int index = sheet.getConditionalFormattings().add();
// Access the newly added FormatConditions via its index
FormatConditionCollection conditionCollection = sheet.getConditionalFormattings().get(index);
// Define a CellsArea on which conditional formatting will be applicable
CellArea area = CellArea.createCellArea("A1", "I20");
// Add area to the instance of FormatConditions
conditionCollection.addArea(area);
// Add a condition to the instance of FormatConditions. For this case, the condition type is expression, which is based on
// some formula
index = conditionCollection.addCondition(FormatConditionType.EXPRESSION);
// Access the newly added FormatCondition via its index
FormatCondition formatCondirion = conditionCollection.get(index);
// Set the formula for the FormatCondition. Formula uses the Excel's built-in functions as discussed earlier in this
// article
formatCondirion.setFormula1("=MOD(ROW(),2)=0");
// Set the background color and patter for the FormatCondition's Style
formatCondirion.getStyle().setBackgroundColor(Color.getBlue());
formatCondirion.getStyle().setPattern(BackgroundType.SOLID);
// Save the result on disk
book.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AssignMacroToFormControl.class);
Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);
int moduleIdx = workbook.getVbaProject().getModules().add(sheet);
VbaModule module = workbook.getVbaProject().getModules().get(moduleIdx);
module.setCodes("Sub ShowMessage()" + "\r\n" +
" MsgBox \"Welcome to Aspose!\"" + "\r\n" +
"End Sub");
Button button = (Button) sheet.getShapes().addShape(MsoDrawingType.BUTTON, 2, 0, 2, 0, 28, 80);
button.setPlacement(PlacementType.FREE_FLOATING);
button.getFont().setName("Tahoma");
button.getFont().setBold(true);
button.getFont().setColor(Color.getBlue());
button.setText("Aspose");
button.setMacroName(sheet.getName() + ".ShowMessage");
workbook.save(dataDir + "Output.xlsm");
System.out.println("File saved");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AutoFitRowsforMergedCells.class);
// Instantiate a new Workbook
Workbook wb = new Workbook();
// Get the first (default) worksheet
Worksheet _worksheet = wb.getWorksheets().get(0);
// Create a range A1:B1
Range range = _worksheet.getCells().createRange(0, 0, 1, 2);
// Merge the cells
range.merge();
// Insert value to the merged cell A1
_worksheet.getCells().get(0, 0).setValue(
"A quick brown fox jumps over the lazy dog. A quick brown fox jumps over the lazy dog....end");
// Create a style object
Style style = _worksheet.getCells().get(0, 0).getStyle();
// Set wrapping text on
style.setTextWrapped(true);
// Apply the style to the cell
_worksheet.getCells().get(0, 0).setStyle(style);
// Create an object for AutoFitterOptions
AutoFitterOptions options = new AutoFitterOptions();
// Set auto-fit for merged cells
options.setAutoFitMergedCells(true);
// Autofit rows in the sheet(including the merged cells)
_worksheet.autoFitRows(options);
// Save the Excel file
wb.save(dataDir + "autofitmergedcells.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(AutomaticallyrefreshOLEobject.class);
// Create workbook object from your sample excel file
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
// Set auto load property of first ole object to true
sheet.getOleObjects().get(0).setAutoLoad(true);
// Save the worbook in xlsx format
wb.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class CustomEngine extends AbstractCalculationEngine {
public void calculate(CalculationData data) {
// Check the forumla name and calculate it yourself
if (data.getFunctionName().equals("MyCompany.CustomFunction")) {
// This is our calculated value
data.setCalculatedValue("Aspose.Cells.");
}
}
}
public void Run() {
// TODO Auto-generated method stub
// Create a workbook
Workbook wb = new Workbook();
// Accesss first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Add some text in cell A1
ws.getCells().get("A1").putValue("Welcome to ");
// Create a calculation options with custom engine
CalculationOptions opts = new CalculationOptions();
opts.setCustomEngine(new CustomEngine());
// This line shows how you can call your own custom function without
// a need to write it in any worksheet cell
// After the execution of this line, it will return
// Welcome to Aspose.Cells.
Object ret = ws.calculateFormula("=A1 & MyCompany.CustomFunction()", opts);
// Print the calculated value on Console
System.out.println("Calculated Value: " + ret.toString());
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CalculateIFNAfunction.class);
// Create new workbook
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Add data for VLOOKUP
worksheet.getCells().get("A1").putValue("Apple");
worksheet.getCells().get("A2").putValue("Orange");
worksheet.getCells().get("A3").putValue("Banana");
// Access cell A5 and A6
Cell cellA5 = worksheet.getCells().get("A5");
Cell cellA6 = worksheet.getCells().get("A6");
// Assign IFNA formula to A5 and A6
cellA5.setFormula("=IFNA(VLOOKUP(\"Pear\",$A$1:$A$3,1,0),\"Not found\")");
cellA6.setFormula("=IFNA(VLOOKUP(\"Orange\",$A$1:$A$3,1,0),\"Not found\")");
// Caclulate the formula of workbook
workbook.calculateFormula();
// Print the values of A5 and A6
System.out.println(cellA5.getStringValue());
System.out.println(cellA6.getStringValue());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CalculatePageSetupScalingFactor.class);
// Create workbook object
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Put some data in these cells
worksheet.getCells().get("A4").putValue("Test");
worksheet.getCells().get("S4").putValue("Test");
// Set paper size
worksheet.getPageSetup().setPaperSize(PaperSizeType.PAPER_A_4);
// Set fit to pages wide as 1
worksheet.getPageSetup().setFitToPagesWide(1);
// Calculate page scale via sheet render
SheetRender sr = new SheetRender(worksheet, new ImageOrPrintOptions());
// Write the page scale value
System.out.println(sr.getPageScale());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CalculateWidthAndHeightOfCell.class);
// Create workbook object
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access cell B2 and add some value inside it
Cell cell = worksheet.getCells().get("B2");
cell.putValue("Welcome to Aspose!");
// Enlarge its font to size 16
Style style = cell.getStyle();
style.getFont().setSize(16);
cell.setStyle(style);
// Calculate the width and height of the cell value in unit of pixels
int widthOfValue = cell.getWidthOfValue();
int heightOfValue = cell.getHeightOfValue();
// Print both values
System.out.println("Width of Cell Value: " + widthOfValue);
System.out.println("Height of Cell Value: " + heightOfValue);
// Set the row height and column width to adjust/fit the cell value inside cell
worksheet.getCells().setColumnWidthPixel(1, widthOfValue);
worksheet.getCells().setRowHeightPixel(1, heightOfValue);
// Save the output excel file
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(CalculationOfArrayFormula.class);
// Create workbook from source excel file
Workbook workbook = new Workbook(dataDir + "DataTable.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// When you will put 100 in B1, then all Data Table values formatted as Yellow will become 120
worksheet.getCells().get("B1").putValue(100);
// Calculate formula, now it also calculates Data Table array formula
workbook.calculateFormula();
// Save the workbook in pdf format
workbook.save(dataDir + "output.pdf");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CalculationofExcelMINIFSandMAXIFSfunctions.class) + "articles/";
// Load your source workbook containing MINIFS and MAXIFS functions
Workbook wb = new Workbook(dataDir + "sample_MINIFS_MAXIFS.xlsx");
// Perform Aspose.Cells formula calculation
wb.calculateFormula();
// Save the calculations result in pdf format
PdfSaveOptions opts = new PdfSaveOptions();
opts.setOnePagePerSheet(true);
wb.save(dataDir + "CalculationofExcel_out.pdf", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(CellsIterator.class);
// Load a file in an instance of Workbook
Workbook book = new Workbook(dataDir + "sample.xlsx");
// Get the iterator from Cells collection
Iterator cellIterator = book.getWorksheets().get(0).getCells().iterator();
// Traverse cells in the collection
while (cellIterator.hasNext()) {
Cell cell = (Cell) cellIterator.next();
;
System.out.println(cell.getName() + " " + cell.getValue());
}
// Get iterator from an object of Row
Iterator rowIterator = book.getWorksheets().get(0).getCells().getRows().get(0).iterator();
// Traverse cells in the given row
while (rowIterator.hasNext()) {
Cell cell = (Cell) rowIterator.next();
System.out.println(cell.getName() + " " + cell.getValue());
}
// Get iterator from an object of Range
Iterator rangeIterator = book.getWorksheets().get(0).getCells().createRange("A1:B10").iterator();
// Traverse cells in the range
while (rangeIterator.hasNext()) {
Cell cell = (Cell) rangeIterator.next();
System.out.println(cell.getName() + " " + cell.getValue());
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ChangeAdjustmentValuesOfShape.class);
// Create workbook object from source excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access first three shapes of the worksheet
Shape shape1 = worksheet.getShapes().get(0);
Shape shape2 = worksheet.getShapes().get(1);
Shape shape3 = worksheet.getShapes().get(2);
// Change the adjustment values of the shapes
shape1.getGeometry().getShapeAdjustValues().get(0).setValue(0.5d);
shape2.getGeometry().getShapeAdjustValues().get(0).setValue(0.8d);
shape3.getGeometry().getShapeAdjustValues().get(0).setValue(0.5d);
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ChangeCharacterSpacing.class) + "articles/";
// Load your excel file inside a workbook obect
Workbook wb = new Workbook(dataDir + "character-spacing.xlsx");
// Access your text box which is also a shape object from shapes collection
Shape shape = wb.getWorksheets().get(0).getShapes().get(0);
// Access the first font setting object via GetCharacters() method
ArrayList<FontSetting> lst = shape.getCharacters();
FontSetting fs = lst.get(0);
// Set the character spacing to point 4
fs.getTextOptions().setSpacing(4);
// Save the workbook in xlsx format
wb.save(dataDir + "CCSpacing_out.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ChangeDataSource.class);
// Load sample excel file
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access the first sheet which contains chart
Worksheet source = wb.getWorksheets().get(0);
// Add another sheet named DestSheet
Worksheet destination = wb.getWorksheets().add("DestSheet");
// Set CopyOptions.ReferToDestinationSheet to true
CopyOptions options = new CopyOptions();
options.setReferToDestinationSheet(true);
/*
* Copy all the rows of source worksheet to destination worksheet which includes chart as well The chart data source will
* now refer to DestSheet
*/
destination.getCells().copyRows(source.getCells(), 0, 0, source.getCells().getMaxDisplayRange().getRowCount(),
options);
// Save workbook in xlsx format
wb.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ChangeFontonspecificUnicodecharacters.class);
// Create workbook object
Workbook workbook = new Workbook();
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access cells
Cell cell1 = worksheet.getCells().get("A1");
Cell cell2 = worksheet.getCells().get("B1");
// Set the styles of both cells to Times New Roman
Style style = cell1.getStyle();
style.getFont().setName("Times New Roman");
cell1.setStyle(style);
cell2.setStyle(style);
// Put the values inside the cell
cell1.putValue("Hello without Non-Breaking Hyphen");
cell2.putValue("Hello" + (char) (8209) + " with Non-Breaking Hyphen");
// Autofit the columns
worksheet.autoFitColumns();
// Save to Pdf without setting PdfSaveOptions.IsFontSubstitutionCharGranularity
workbook.save(dataDir + "output.pdf");
// Save to Pdf after setting PdfSaveOptions.IsFontSubstitutionCharGranularity to true
PdfSaveOptions opts = new PdfSaveOptions();
opts.setFontSubstitutionCharGranularity(true);
workbook.save(dataDir + "output2.pdf", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ChangeHtmlLinkTarget.class);
String inputPath = dataDir + "Sample1.xlsx";
String outputPath = dataDir + "Output.html";
Workbook workbook = new Workbook(inputPath);
HtmlSaveOptions opts = new HtmlSaveOptions();
opts.setLinkTargetType(HtmlLinkTargetType.SELF);
workbook.save(outputPath, opts);
System.out.println("File saved " + outputPath);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ChangeHTMLLinkTargetType.class);
Workbook workbook = new Workbook(dataDir + "source.xlsx");
HtmlSaveOptions opts = new HtmlSaveOptions();
opts.setLinkTargetType(HtmlLinkTargetType.SELF);
workbook.save(dataDir + "out.html", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(Orientation.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Accessing the added worksheet in the Excel file
int sheetIndex = workbook.getWorksheets().add();
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex);
Cells cells = worksheet.getCells();
// Adding the current system date to "A1" cell
Cell cell = cells.get("A1");
Style style = cell.getStyle();
// Adding some value to the "A1" cell
cell.setValue("Visit Aspose!");
// Setting the text direction from right to left
Style style1 = cell.getStyle();
style1.setTextDirection(TextDirectionType.RIGHT_TO_LEFT);
cell.setStyle(style1);
// Saved style
cell.setStyle(style1);
// Saving the modified Excel file in default format
workbook.save(dataDir + "book1.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ChangeTextDirectionofComment.class);
// Instantiate a new Workbook
Workbook wb = new Workbook();
// Get the first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
// Add a comment to A1 cell
Comment comment = sheet.getComments().get(sheet.getComments().add("A1"));
// Set its vertical alignment setting
comment.getCommentShape().setTextVerticalAlignment(TextAlignmentType.CENTER);
// Set its horizontal alignment setting
comment.getCommentShape().setTextHorizontalAlignment(TextAlignmentType.RIGHT);
// Set the Text Direction - Right-to-Left
comment.getCommentShape().setTextDirection(TextDirectionType.RIGHT_TO_LEFT);
// Set the Comment note
comment.setNote("This is my Comment Text. This is test");
// Save the Excel file
wb.save(dataDir + "outCommentShape1.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ChangingLayoutofPivotTable.class);
// Create workbook object from source excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access first pivot table
PivotTable pivotTable = worksheet.getPivotTables().get(0);
// 1 - Show the pivot table in compact form
pivotTable.showInCompactForm();
// Refresh the pivot table
pivotTable.refreshData();
pivotTable.calculateData();
// Save the output
workbook.save("CompactForm.xlsx");
// 2 - Show the pivot table in outline form
pivotTable.showInOutlineForm();
// Refresh the pivot table
pivotTable.refreshData();
pivotTable.calculateData();
// Save the output
workbook.save("OutlineForm.xlsx");
// 3 - Show the pivot table in tabular form
pivotTable.showInTabularForm();
// Refresh the pivot table
pivotTable.refreshData();
pivotTable.calculateData();
// Save the output
workbook.save(dataDir + "TabularForm.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CheckPassword.class) + "articles/";
// Specify password to open inside the load options
LoadOptions opts = new LoadOptions();
opts.setPassword("1234");
// Open the source Excel file with load options
Workbook workbook = new Workbook(dataDir + "Book1.xlsx", opts);
// Check if 567 is Password to modify
boolean ret = workbook.getSettings().getWriteProtection().validatePassword("567");
System.out.println("Is 567 correct Password to modify: " + ret);
// Check if 5678 is Password to modify
ret = workbook.getSettings().getWriteProtection().validatePassword("5678");
System.out.println("Is 5678 correct Password to modify: " + ret);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CheckVBAProjectInWorkbookIsSigned.class);
Workbook workbook = new Workbook(dataDir + "source.xlsm");
System.out.println("VBA Project is Signed: " + workbook.getVbaProject().isSigned());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(CheckVbaProjectSigned.class);
String inputPath = dataDir + "Sample1.xlsx";
Workbook workbook = new Workbook(inputPath);
System.out.println("VBA Project is Signed: " + workbook.getVbaProject().isSigned());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ColumnsIterator.class);
// Load a file in an instance of Workbook
Workbook book = new Workbook(dataDir + "sample.xlsx");
// Get the iterator for ColumnsCollection
Iterator colsIterator = book.getWorksheets().get(0).getCells().getColumns().iterator();
// Traverse columns in the collection
while (colsIterator.hasNext()) {
Column col = (Column) colsIterator.next();
System.out.println(col.getIndex());
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CombineMultipleWorkbooks.class);
// Open the first excel file.
Workbook SourceBook1 = new Workbook(dataDir + "charts.xlsx");
// Define the second source book.
// Open the second excel file.
Workbook SourceBook2 = new Workbook(dataDir + "picture.xlsx");
// Combining the two workbooks
SourceBook1.combine(SourceBook2);
// Save the target book file.
SourceBook1.save(dataDir + "combined.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CombineMultipleWorksheets.class);
Workbook workbook = new Workbook(dataDir + "source.xlsx");
Workbook destWorkbook = new Workbook();
Worksheet destSheet = destWorkbook.getWorksheets().get(0);
int TotalRowCount = 0;
for (int i = 0; i < workbook.getWorksheets().getCount(); i++) {
Worksheet sourceSheet = workbook.getWorksheets().get(i);
Range sourceRange = sourceSheet.getCells().getMaxDisplayRange();
Range destRange = destSheet.getCells().createRange(sourceRange.getFirstRow() + TotalRowCount,
sourceRange.getFirstColumn(), sourceRange.getRowCount(), sourceRange.getColumnCount());
destRange.copy(sourceRange);
TotalRowCount = sourceRange.getRowCount() + TotalRowCount;
}
destWorkbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConditionalFormattingBasedOnFormula.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);
ConditionalFormattingCollection cfs = sheet.getConditionalFormattings();
int index = cfs.add();
FormatConditionCollection fcs = cfs.get(index);
// Sets the conditional format range.
CellArea ca = new CellArea();
ca = new CellArea();
ca.StartRow = 2;
ca.EndRow = 2;
ca.StartColumn = 1;
ca.EndColumn = 1;
fcs.addArea(ca);
// Sets condition formulas.
int conditionIndex = fcs.addCondition(FormatConditionType.EXPRESSION, OperatorType.NONE, "", "");
FormatCondition fc = fcs.get(conditionIndex);
fc.setFormula1("=IF(SUM(B1:B2)>100,TRUE,FALSE)");
fc.getStyle().setBackgroundColor(Color.getRed());
sheet.getCells().get("B3").setFormula("=SUM(B1:B2)");
sheet.getCells().get("C4").setValue("If Sum of B1:B2 is greater than 100, B3 will have RED background");
workbook.save(dataDir + "output.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConditionalFormattingOnCellValue.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);
// Adds an empty conditional formatting
int index = sheet.getConditionalFormattings().add();
FormatConditionCollection fcs = sheet.getConditionalFormattings().get(index);
// Sets the conditional format range.
CellArea ca = new CellArea();
ca.StartRow = 0;
ca.EndRow = 0;
ca.StartColumn = 0;
ca.EndColumn = 0;
fcs.addArea(ca);
// Sets condition formulas.
int conditionIndex = fcs.addCondition(FormatConditionType.CELL_VALUE, OperatorType.BETWEEN, "50", "100");
FormatCondition fc = fcs.get(conditionIndex);
fc.getStyle().setBackgroundColor(Color.getRed());
workbook.save(dataDir + "output.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load excel file containing some data
Workbook workbook = new Workbook("book1.xlsx");
// Create an instance of PdfSaveOptions and pass SaveFormat to the constructor
PdfSaveOptions pdfSaveOpt = new PdfSaveOptions(SaveFormat.PDF);
// Create an instance of PdfSecurityOptions
PdfSecurityOptions securityOptions = new PdfSecurityOptions();
// Set AccessibilityExtractContent to true
securityOptions.setAccessibilityExtractContent(false);
// Set the securityoption in the PdfSaveOptions
pdfSaveOpt.setSecurityOptions(securityOptions);
// Save the workbook to PDF format while passing the object of PdfSaveOptions
workbook.save("outFile.pdf", pdfSaveOpt);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConversionOptions.class);
// Instantiate a new Workbook object
// Open template
Workbook book = new Workbook(dataDir + "book1.xlsx");
// Get the first worksheet
Worksheet sheet = book.getWorksheets().get(0);
// Apply different Image and Print options
ImageOrPrintOptions options = new ImageOrPrintOptions();
// Set Horizontal Resolution
options.setHorizontalResolution(300);
// Set Vertical Resolution
options.setVerticalResolution(300);
// Set Image Format
options.setImageFormat(ImageFormat.getJpeg());
// If you want entire sheet as a singe image
options.setOnePagePerSheet(true);
// Render the sheet with respect to specified image/print options
SheetRender sr = new SheetRender(sheet, options);
// Render/save the image for the sheet
sr.toImage(0, dataDir + "SheetImage.jpg");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertCharttoImageinSVGFormat.class);
// Create workbook object from source Excel file
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the first chart inside the worksheet
Chart chart = worksheet.getCharts().get(0);
// Save the chart into image in SVG format
ImageOrPrintOptions options = new ImageOrPrintOptions();
options.setSaveFormat(SaveFormat.SVG);
chart.toImage(dataDir + "ChartImage.svg", options);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertCSVfiletoXLSX.class);
// Set Multi Encoded Property to True
TxtLoadOptions options = new TxtLoadOptions();
options.setMultiEncoded(true);
// Load the CSV file into Workbook
Workbook workbook = new Workbook(dataDir + "MutliEncoded.csv", options);
// Save it in XLSX format
workbook.save(dataDir + "out.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertRevisionOfXLSBtoXLSM.class);
Workbook workbook = new Workbook(dataDir + "book1.xlsb");
workbook.save(dataDir + ".out.xlsm", SaveFormat.XLSM);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertTextNumericDatatoNumber.class);
Workbook workbook = new Workbook(dataDir + "source.xlsx");
for (int i = 0; i < workbook.getWorksheets().getCount(); i++) {
workbook.getWorksheets().get(i).getCells().convertStringToNumericValue();
}
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertWorkbooktoImage.class);
// Instantiate a new Workbook object
Workbook book = new Workbook(dataDir + "book1.xlsx");
// Apply different Image and Print options
ImageOrPrintOptions options = new ImageOrPrintOptions();
// Set Image Format
options.setImageFormat(ImageFormat.getTiff());
// If you want entire sheet as a single image
options.setOnePagePerSheet(true);
// Render to image
WorkbookRender render = new WorkbookRender(book, options);
render.toImage(dataDir + "output.tiff");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertWorksheettoImage.class);
//Instantiate a new Workbook object
//Open template
Workbook book = new Workbook(dataDir + "book1.xlsx");
//Get the first worksheet
Worksheet sheet = book.getWorksheets().get(0);
//Apply different Image and Print options
ImageOrPrintOptions options = new ImageOrPrintOptions();
//Set Horizontal Resolution
options.setHorizontalResolution(300);
//Set Vertical Resolution
options.setVerticalResolution(300);
//Set TiffCompression
options.setTiffCompression(TiffCompression.COMPRESSION_LZW);
//Set Image Format
options.setImageFormat(ImageFormat.getTiff());
//Set printing page type
options.setPrintingPage(PrintingPageType.DEFAULT);
//Render the sheet with respect to specified image/print options
SheetRender sr = new SheetRender(sheet, options);
//Render/save the image for the sheet
sr.toImage(0, dataDir + "SheetImage.tiff");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertWorksheetToImageByPage.class);
// Create a new Workbook object
// Open a template excel file
Workbook book = new Workbook(dataDir + "bool1.xlsx");
// Get the first worksheet
Worksheet sheet = book.getWorksheets().get(0);
// Define ImageOrPrintOptions
ImageOrPrintOptions options = new ImageOrPrintOptions();
// Set Resolution
options.setHorizontalResolution(200);
options.setVerticalResolution(200);
options.setImageFormat(ImageFormat.getTiff());
// Sheet2Image by page conversion
SheetRender render = new SheetRender(sheet, options);
for (int j = 0; j < render.getPageCount(); j++) {
render.toImage(j, dataDir + sheet.getName() + " Page" + (j + 1) + ".tif");
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertWorksheettoImageFile.class);
// Create a new Workbook object
// Open a template excel file
Workbook book = new Workbook(dataDir + "book.xlsx");
// Get the first worksheet
Worksheet sheet = book.getWorksheets().get(0);
// Define ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
// Specify the image format
imgOptions.setImageFormat(ImageFormat.getJpeg());
// Render the sheet with respect to specified image/print options
SheetRender render = new SheetRender(sheet, imgOptions);
// Render the image for the sheet
render.toImage(0, dataDir + "SheetImage.jpg");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ConvertXLSFileToPDF.class);
//Create a new Workbook
Workbook book = new Workbook(dataDir + "SampleInput.xlsx");
//Save the excel file to PDF format
book.save(dataDir + "output.pdf", SaveFormat.PDF);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyChartFromOneWorksheetToAnother.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "Shapes.xls");
WorksheetCollection ws = workbook.getWorksheets();
Worksheet sheet1 = ws.get("Chart");
Worksheet sheet2 = ws.get("Result");
// get the Chart from first worksheet
Chart chart = sheet1.getCharts().get(0);
ChartShape cshape = chart.getChartObject();
// Copy the Chart to Second Worksheet
sheet2.getShapes().addCopy(cshape, 20, 0, 2, 0);
// Save the workbook
workbook.save(dataDir + "Shapes.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyingMultipleColumns.class);
// Create an instance of Workbook class by loading the existing spreadsheet
Workbook workbook = new Workbook(dataDir + "aspose-sample.xlsx");
// Get the cells collection of worksheet by name Columns
Cells cells = workbook.getWorksheets().get("Columns").getCells();
// Copy the first 3 columns 7th column
cells.copyColumns(cells, 0, 6, 3);
// Save the result on disc
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyingMultipleRows.class);
// Create an instance of Workbook class by loading the existing spreadsheet
Workbook workbook = new Workbook(dataDir + "aspose-sample.xlsx");
// Get the cells collection of worksheet by name Rows
Cells cells = workbook.getWorksheets().get("Rows").getCells();
// Copy the first 3 rows to 7th row
cells.copyRows(cells, 0, 6, 3);
// Save the result on disc
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyingSingleColumn.class);
// Create an instance of Workbook class by loading the existing spreadsheet
Workbook workbook = new Workbook(dataDir + "aspose-sample.xlsx");
// Get the cells collection of first workshet
Cells cells = workbook.getWorksheets().get("Columns").getCells();
// Copy the first column to next 10 columns
for (int i = 1; i <= 10; i++) {
cells.copyColumn(cells, 0, i);
}
// Save the result on disc
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyingSingleRow.class);
// Create an instance of Workbook class by loading the existing spreadsheet
Workbook workbook = new Workbook(dataDir + "aspose-sample.xlsx");
// Get the cells collection of first worksheet
Cells cells = workbook.getWorksheets().get(0).getCells();
// Copy the first row to next 10 rows
for (int i = 1; i <= 10; i++) {
cells.copyRow(cells, 0, i);
}
// Save the result on disc
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyPicturefromOneWorksheetToAnother.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "Shapes.xls");
WorksheetCollection ws = workbook.getWorksheets();
Worksheet sheet1 = ws.get("Picture");
Worksheet sheet2 = ws.get("Result");
// get the Picture from first worksheet
Picture pic = sheet1.getPictures().get(0);
ByteArrayInputStream bis = new ByteArrayInputStream(pic.getData());
// Copy the Picture to Second Worksheet
sheet2.getPictures().add(pic.getUpperLeftRow(), pic.getUpperLeftColumn(), pic.getWidthScale(),
pic.getHeightScale(), bis);
// Save the workbook
workbook.save(dataDir + "Shapes.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyRangeDataOnly.class);
// Instantiate a new Workbook
Workbook workbook = new Workbook();
// Get the first Worksheet Cells
Cells cells = workbook.getWorksheets().get(0).getCells();
// Fill some sample data into the cells
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 10; j++) {
cells.get(i, j).putValue(i + "," + j);
}
}
// Create a range (A1:D3).
Range range = cells.createRange("A1", "D3");
// Create a style object.
Style style = workbook.createStyle();
// Specify the font attribute.
style.getFont().setName("Calibri");
// Specify the shading color.
style.setForegroundColor(Color.getYellow());
style.setPattern(BackgroundType.SOLID);
// Specify the border attributes.
style.getBorders().getByBorderType(BorderType.TOP_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.TOP_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.LEFT_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.LEFT_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.RIGHT_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.RIGHT_BORDER).setColor(Color.getBlue());
// Create the styleflag object.
StyleFlag flag = new StyleFlag();
// Implement font attribute
flag.setFontName(true);
// Implement the shading / fill color.
flag.setCellShading(true);
// Implment border attributes.
flag.setBorders(true);
// Set the Range style.
range.applyStyle(style, flag);
// Create a second range (L9:O11)
Range range2 = cells.createRange("L9", "O11");
// Copy the range data only.
range2.copyData(range);
// Save the Excel file.
workbook.save(dataDir + "CopyRangeData.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyRangeDataWithStyle.class);
// Instantiate a new Workbook
Workbook workbook = new Workbook();
// Get the first Worksheet Cells
Cells cells = workbook.getWorksheets().get(0).getCells();
// Fill some sample data into the cells
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 10; j++) {
cells.get(i, j).putValue(i + "," + j);
}
}
// Create a range (A1:D3).
Range range = cells.createRange("A1", "D3");
// Create a style object.
Style style = workbook.createStyle();
// Specify the font attribute.
style.getFont().setName("Calibri");
// Specify the shading color.
style.setForegroundColor(Color.getYellow());
style.setPattern(BackgroundType.SOLID);
// Specify the border attributes.
style.getBorders().getByBorderType(BorderType.TOP_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.TOP_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.LEFT_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.LEFT_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.RIGHT_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.RIGHT_BORDER).setColor(Color.getBlue());
// Create the styleflag object.
StyleFlag flag = new StyleFlag();
// Implement font attribute
flag.setFontName(true);
// Implement the shading / fill color.
flag.setCellShading(true);
// Implment border attributes.
flag.setBorders(true);
// Set the Range style.
range.applyStyle(style, flag);
// Create a second range (L9:O11)
Range range2 = cells.createRange("L9", "O11");
// Copy the range data with formatting.
range2.copy(range);
// Save the Excel file.
workbook.save(dataDir + "CopyRangeDataWithFormatting.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyRangeStyleOnly.class);
// Instantiate a new Workbook
Workbook workbook = new Workbook();
// Get the first Worksheet Cells
Cells cells = workbook.getWorksheets().get(0).getCells();
// Fill some sample data into the cells
for (int i = 0; i < 50; i++) {
for (int j = 0; j < 10; j++) {
cells.get(i, j).putValue(i + "," + j);
}
}
// Create a range (A1:D3).
Range range = cells.createRange("A1", "D3");
// Create a style object.
Style style = workbook.createStyle();
// Specify the font attribute.
style.getFont().setName("Calibri");
// Specify the shading color.
style.setForegroundColor(Color.getYellow());
style.setPattern(BackgroundType.SOLID);
// Specify the border attributes.
style.getBorders().getByBorderType(BorderType.TOP_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.TOP_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.LEFT_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.LEFT_BORDER).setColor(Color.getBlue());
style.getBorders().getByBorderType(BorderType.RIGHT_BORDER).setLineStyle(CellBorderType.THIN);
style.getBorders().getByBorderType(BorderType.RIGHT_BORDER).setColor(Color.getBlue());
// Create the styleflag object.
StyleFlag flag = new StyleFlag();
// Implement font attribute
flag.setFontName(true);
// Implement the shading / fill color.
flag.setCellShading(true);
// Implment border attributes.
flag.setBorders(true);
// Set the Range style.
range.applyStyle(style, flag);
// Create a second range (L9:O11)
Range range2 = cells.createRange("L9", "O11");
// Copy the range style only.
range2.copyStyle(range);
// Save the Excel file.
workbook.save(dataDir + "CopyRangeStyleOnly.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyRowHeights.class);
// Create workbook object
Workbook workbook = new Workbook();
// Source worksheet
Worksheet srcSheet = workbook.getWorksheets().get(0);
// Add destination worksheet
Worksheet dstSheet = workbook.getWorksheets().add("Destination Sheet");
// Set the row height of the 4th row
// This row height will be copied to destination range
srcSheet.getCells().setRowHeight(3, 50);
// Create source range to be copied
Range srcRange = srcSheet.getCells().createRange("A1:D10");
// Create destination range in destination worksheet
Range dstRange = dstSheet.getCells().createRange("A1:D10");
// PasteOptions, we want to copy row heights of source range to destination range
PasteOptions opts = new PasteOptions();
opts.setPasteType(PasteType.ROW_HEIGHTS);
// Copy source range to destination range with paste options
dstRange.copy(srcRange, opts);
// Write informative message in cell D4 of destination worksheet
dstSheet.getCells().get("D4").putValue("Row heights of source range copied to destination range");
// Save the workbook in xlsx format
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopySparkline.class);
// Create workbook from source Excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the first sparkline group
SparklineGroup group = worksheet.getSparklineGroupCollection().get(0);
// Add Data Ranges and Locations inside this sparkline group
group.getSparklineCollection().add("D5:O5", 4, 15);
group.getSparklineCollection().add("D6:O6", 5, 15);
group.getSparklineCollection().add("D7:O7", 6, 15);
group.getSparklineCollection().add("D8:O8", 7, 15);
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CopyWorksheetBetweenWorkbooks.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "Controls.xls");
WorksheetCollection ws = workbook.getWorksheets();
Worksheet sheet1 = ws.get("Control");
Worksheet sheet2 = ws.get("Result");
// Get the Shapes from the "Control" worksheet.
ShapeCollection shapes = sheet1.getShapes();
// Copy the Textbox to Second Worksheet
sheet2.getShapes().addCopy(shapes.get(0), 5, 0, 2, 0);
// Copy the oval shape to Second Worksheet
sheet2.getShapes().addCopy(shapes.get(1), 10, 0, 2, 0);
// Save the workbook
workbook.save(dataDir + "Controls.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreatePieChartWithLeaderLines.class);
// Create an instance of Workbook in XLSX format
Workbook workbook = new Workbook(FileFormatType.XLSX);
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Add two columns of data
worksheet.getCells().get("A1").putValue("Retail");
worksheet.getCells().get("A2").putValue("Services");
worksheet.getCells().get("A3").putValue("Info & Communication");
worksheet.getCells().get("A4").putValue("Transport Equip");
worksheet.getCells().get("A5").putValue("Construction");
worksheet.getCells().get("A6").putValue("Other Products");
worksheet.getCells().get("A7").putValue("Wholesale");
worksheet.getCells().get("A8").putValue("Land Transport");
worksheet.getCells().get("A9").putValue("Air Transport");
worksheet.getCells().get("A10").putValue("Electric Appliances");
worksheet.getCells().get("A11").putValue("Securities");
worksheet.getCells().get("A12").putValue("Textiles & Apparel");
worksheet.getCells().get("A13").putValue("Machinery");
worksheet.getCells().get("A14").putValue("Metal Products");
worksheet.getCells().get("A15").putValue("Cash");
worksheet.getCells().get("A16").putValue("Banks");
worksheet.getCells().get("B1").putValue(10.4);
worksheet.getCells().get("B2").putValue(5.2);
worksheet.getCells().get("B3").putValue(6.4);
worksheet.getCells().get("B4").putValue(10.4);
worksheet.getCells().get("B5").putValue(7.9);
worksheet.getCells().get("B6").putValue(4.1);
worksheet.getCells().get("B7").putValue(3.5);
worksheet.getCells().get("B8").putValue(5.7);
worksheet.getCells().get("B9").putValue(3);
worksheet.getCells().get("B10").putValue(14.7);
worksheet.getCells().get("B11").putValue(3.6);
worksheet.getCells().get("B12").putValue(2.8);
worksheet.getCells().get("B13").putValue(7.8);
worksheet.getCells().get("B14").putValue(2.4);
worksheet.getCells().get("B15").putValue(1.8);
worksheet.getCells().get("B16").putValue(10.1);
// Create a pie chart and add it to the collection of charts
int id = worksheet.getCharts().add(ChartType.PIE, 3, 3, 23, 13);
// Access newly created Chart instance
Chart chart = worksheet.getCharts().get(id);
// Set series data range
chart.getNSeries().add("B1:B16", true);
// Set category data range
chart.getNSeries().setCategoryData("A1:A16");
// Turn off legend
chart.setShowLegend(false);
// Access data labels
DataLabels dataLabels = chart.getNSeries().get(0).getDataLabels();
// Turn on category names
dataLabels.setShowCategoryName(true);
// Turn on percentage format
dataLabels.setShowPercentage(true);
// Set position
dataLabels.setPosition(LabelPositionType.OUTSIDE_END);
// Set separator
dataLabels.setSeparator(DataLablesSeparatorType.COMMA);
//Turn on leader lines
chart.getNSeries().get(0).setHasLeaderLines(true);
//Calculate chart
chart.calculate();
//You need to move DataLabels a little leftward or rightward depending on their position
//to show leader lines
int DELTA = 100;
for (int i = 0; i < chart.getNSeries().get(0).getPoints().getCount(); i++)
{
int X = chart.getNSeries().get(0).getPoints().get(i).getDataLabels().getX();
//If it is greater than 2000, then move the X position a little right
//otherwise move the X position a little left
if (X > 2000)
chart.getNSeries().get(0).getPoints().get(i).getDataLabels().setX(X + DELTA);
else
chart.getNSeries().get(0).getPoints().get(i).getDataLabels().setX(X - DELTA);
}
//In order to save the chart image, create an instance of ImageOrPrintOptions
ImageOrPrintOptions anOption = new ImageOrPrintOptions();
//Set image format
anOption.setImageFormat(ImageFormat.getPng());
//Set resolution
anOption.setHorizontalResolution(200);
anOption.setVerticalResolution(200);
//Render chart to image
chart.toImage(dataDir + "output.png", anOption);
//Save the workbook to see chart inside the Excel
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreatePivotChartbasedonPivotTable.class);
// Instantiating an Workbook object
Workbook workbook = new Workbook(dataDir + "pivotTable_test.xls");
// Adding a new sheet
int sheetIndex = workbook.getWorksheets().add(SheetType.CHART);
Worksheet sheet3 = workbook.getWorksheets().get(sheetIndex);
// Naming the sheet
sheet3.setName("PivotChart");
// Adding a column chart
int chartIndex = sheet3.getCharts().add(ChartType.COLUMN, 0, 5, 28, 16);
Chart chart = sheet3.getCharts().get(chartIndex);
// Setting the pivot chart data source
chart.setPivotSource("PivotTable!PivotTable1");
chart.setHidePivotFieldButtons(false);
// Saving the Excel file
workbook.save(dataDir + "pivotChart_test.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreatePivotTable.class);
// Instantiating an Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Name the sheet
sheet.setName("Data");
Cells cells = sheet.getCells();
// Setting the values to the cells
Cell cell = cells.get("A1");
cell.setValue("Employee");
cell = cells.get("B1");
cell.setValue("Quarter");
cell = cells.get("C1");
cell.setValue("Product");
cell = cells.get("D1");
cell.setValue("Continent");
cell = cells.get("E1");
cell.setValue("Country");
cell = cells.get("F1");
cell.setValue("Sale");
cell = cells.get("A2");
cell.setValue("David");
cell = cells.get("A3");
cell.setValue("David");
cell = cells.get("A4");
cell.setValue("David");
cell = cells.get("A5");
cell.setValue("David");
cell = cells.get("A6");
cell.setValue("James");
cell = cells.get("A7");
cell.setValue("James");
cell = cells.get("A8");
cell.setValue("James");
cell = cells.get("A9");
cell.setValue("James");
cell = cells.get("A10");
cell.setValue("James");
cell = cells.get("A11");
cell.setValue("Miya");
cell = cells.get("A12");
cell.setValue("Miya");
cell = cells.get("A13");
cell.setValue("Miya");
cell = cells.get("A14");
cell.setValue("Miya");
cell = cells.get("A15");
cell.setValue("Miya");
cell = cells.get("A16");
cell.setValue("Miya");
cell = cells.get("A17");
cell.setValue("Miya");
cell = cells.get("A18");
cell.setValue("Elvis");
cell = cells.get("A19");
cell.setValue("Elvis");
cell = cells.get("A20");
cell.setValue("Elvis");
cell = cells.get("A21");
cell.setValue("Elvis");
cell = cells.get("A22");
cell.setValue("Elvis");
cell = cells.get("A23");
cell.setValue("Elvis");
cell = cells.get("A24");
cell.setValue("Elvis");
cell = cells.get("A25");
cell.setValue("Jean");
cell = cells.get("A26");
cell.setValue("Jean");
cell = cells.get("A27");
cell.setValue("Jean");
cell = cells.get("A28");
cell.setValue("Ada");
cell = cells.get("A29");
cell.setValue("Ada");
cell = cells.get("A30");
cell.setValue("Ada");
cell = cells.get("B2");
cell.setValue("1");
cell = cells.get("B3");
cell.setValue("2");
cell = cells.get("B4");
cell.setValue("3");
cell = cells.get("B5");
cell.setValue("4");
cell = cells.get("B6");
cell.setValue("1");
cell = cells.get("B7");
cell.setValue("2");
cell = cells.get("B8");
cell.setValue("3");
cell = cells.get("B9");
cell.setValue("4");
cell = cells.get("B10");
cell.setValue("4");
cell = cells.get("B11");
cell.setValue("1");
cell = cells.get("B12");
cell.setValue("1");
cell = cells.get("B13");
cell.setValue("2");
cell = cells.get("B14");
cell.setValue("2");
cell = cells.get("B15");
cell.setValue("3");
cell = cells.get("B16");
cell.setValue("4");
cell = cells.get("B17");
cell.setValue("4");
cell = cells.get("B18");
cell.setValue("1");
cell = cells.get("B19");
cell.setValue("1");
cell = cells.get("B20");
cell.setValue("2");
cell = cells.get("B21");
cell.setValue("3");
cell = cells.get("B22");
cell.setValue("3");
cell = cells.get("B23");
cell.setValue("4");
cell = cells.get("B24");
cell.setValue("4");
cell = cells.get("B25");
cell.setValue("1");
cell = cells.get("B26");
cell.setValue("2");
cell = cells.get("B27");
cell.setValue("3");
cell = cells.get("B28");
cell.setValue("1");
cell = cells.get("B29");
cell.setValue("2");
cell = cells.get("B30");
cell.setValue("3");
cell = cells.get("C2");
cell.setValue("Maxilaku");
cell = cells.get("C3");
cell.setValue("Maxilaku");
cell = cells.get("C4");
cell.setValue("Chai");
cell = cells.get("C5");
cell.setValue("Maxilaku");
cell = cells.get("C6");
cell.setValue("Chang");
cell = cells.get("C7");
cell.setValue("Chang");
cell = cells.get("C8");
cell.setValue("Chang");
cell = cells.get("C9");
cell.setValue("Chang");
cell = cells.get("C10");
cell.setValue("Chang");
cell = cells.get("C11");
cell.setValue("Geitost");
cell = cells.get("C12");
cell.setValue("Chai");
cell = cells.get("C13");
cell.setValue("Geitost");
cell = cells.get("C14");
cell.setValue("Geitost");
cell = cells.get("C15");
cell.setValue("Maxilaku");
cell = cells.get("C16");
cell.setValue("Geitost");
cell = cells.get("C17");
cell.setValue("Geitost");
cell = cells.get("C18");
cell.setValue("Ikuru");
cell = cells.get("C19");
cell.setValue("Ikuru");
cell = cells.get("C20");
cell.setValue("Ikuru");
cell = cells.get("C21");
cell.setValue("Ikuru");
cell = cells.get("C22");
cell.setValue("Ipoh Coffee");
cell = cells.get("C23");
cell.setValue("Ipoh Coffee");
cell = cells.get("C24");
cell.setValue("Ipoh Coffee");
cell = cells.get("C25");
cell.setValue("Chocolade");
cell = cells.get("C26");
cell.setValue("Chocolade");
cell = cells.get("C27");
cell.setValue("Chocolade");
cell = cells.get("C28");
cell.setValue("Chocolade");
cell = cells.get("C29");
cell.setValue("Chocolade");
cell = cells.get("C30");
cell.setValue("Chocolade");
cell = cells.get("D2");
cell.setValue("Asia");
cell = cells.get("D3");
cell.setValue("Asia");
cell = cells.get("D4");
cell.setValue("Asia");
cell = cells.get("D5");
cell.setValue("Asia");
cell = cells.get("D6");
cell.setValue("Europe");
cell = cells.get("D7");
cell.setValue("Europe");
cell = cells.get("D8");
cell.setValue("Europe");
cell = cells.get("D9");
cell.setValue("Europe");
cell = cells.get("D10");
cell.setValue("Europe");
cell = cells.get("D11");
cell.setValue("America");
cell = cells.get("D12");
cell.setValue("America");
cell = cells.get("D13");
cell.setValue("America");
cell = cells.get("D14");
cell.setValue("America");
cell = cells.get("D15");
cell.setValue("America");
cell = cells.get("D16");
cell.setValue("America");
cell = cells.get("D17");
cell.setValue("America");
cell = cells.get("D18");
cell.setValue("Europe");
cell = cells.get("D19");
cell.setValue("Europe");
cell = cells.get("D20");
cell.setValue("Europe");
cell = cells.get("D21");
cell.setValue("Oceania");
cell = cells.get("D22");
cell.setValue("Oceania");
cell = cells.get("D23");
cell.setValue("Oceania");
cell = cells.get("D24");
cell.setValue("Oceania");
cell = cells.get("D25");
cell.setValue("Africa");
cell = cells.get("D26");
cell.setValue("Africa");
cell = cells.get("D27");
cell.setValue("Africa");
cell = cells.get("D28");
cell.setValue("Africa");
cell = cells.get("D29");
cell.setValue("Africa");
cell = cells.get("D30");
cell.setValue("Africa");
cell = cells.get("E2");
cell.setValue("China");
cell = cells.get("E3");
cell.setValue("India");
cell = cells.get("E4");
cell.setValue("Korea");
cell = cells.get("E5");
cell.setValue("India");
cell = cells.get("E6");
cell.setValue("France");
cell = cells.get("E7");
cell.setValue("France");
cell = cells.get("E8");
cell.setValue("Germany");
cell = cells.get("E9");
cell.setValue("Italy");
cell = cells.get("E10");
cell.setValue("France");
cell = cells.get("E11");
cell.setValue("U.S.");
cell = cells.get("E12");
cell.setValue("U.S.");
cell = cells.get("E13");
cell.setValue("Brazil");
cell = cells.get("E14");
cell.setValue("U.S.");
cell = cells.get("E15");
cell.setValue("U.S.");
cell = cells.get("E16");
cell.setValue("Canada");
cell = cells.get("E17");
cell.setValue("U.S.");
cell = cells.get("E18");
cell.setValue("Italy");
cell = cells.get("E19");
cell.setValue("France");
cell = cells.get("E20");
cell.setValue("Italy");
cell = cells.get("E21");
cell.setValue("New Zealand");
cell = cells.get("E22");
cell.setValue("Australia");
cell = cells.get("E23");
cell.setValue("Australia");
cell = cells.get("E24");
cell.setValue("New Zealand");
cell = cells.get("E25");
cell.setValue("S.Africa");
cell = cells.get("E26");
cell.setValue("S.Africa");
cell = cells.get("E27");
cell.setValue("S.Africa");
cell = cells.get("E28");
cell.setValue("Egypt");
cell = cells.get("E29");
cell.setValue("Egypt");
cell = cells.get("E30");
cell.setValue("Egypt");
cell = cells.get("F2");
cell.setValue(2000);
cell = cells.get("F3");
cell.setValue(500);
cell = cells.get("F4");
cell.setValue(1200);
cell = cells.get("F5");
cell.setValue(1500);
cell = cells.get("F6");
cell.setValue(500);
cell = cells.get("F7");
cell.setValue(1500);
cell = cells.get("F8");
cell.setValue(800);
cell = cells.get("F9");
cell.setValue(900);
cell = cells.get("F10");
cell.setValue(500);
cell = cells.get("F11");
cell.setValue(1600);
cell = cells.get("F12");
cell.setValue(600);
cell = cells.get("F13");
cell.setValue(2000);
cell = cells.get("F14");
cell.setValue(500);
cell = cells.get("F15");
cell.setValue(900);
cell = cells.get("F16");
cell.setValue(700);
cell = cells.get("F17");
cell.setValue(1400);
cell = cells.get("F18");
cell.setValue(1350);
cell = cells.get("F19");
cell.setValue(300);
cell = cells.get("F20");
cell.setValue(500);
cell = cells.get("F21");
cell.setValue(1000);
cell = cells.get("F22");
cell.setValue(1500);
cell = cells.get("F23");
cell.setValue(1500);
cell = cells.get("F24");
cell.setValue(1600);
cell = cells.get("F25");
cell.setValue(1000);
cell = cells.get("F26");
cell.setValue(1200);
cell = cells.get("F27");
cell.setValue(1300);
cell = cells.get("F28");
cell.setValue(1500);
cell = cells.get("F29");
cell.setValue(1400);
cell = cells.get("F30");
cell.setValue(1000);
// Adding a new sheet
int sheetIndex = workbook.getWorksheets().add();
Worksheet sheet2 = workbook.getWorksheets().get(sheetIndex);
// Naming the sheet
sheet2.setName("PivotTable");
// Getting the pivottables collection in the sheet
PivotTableCollection pivotTables = sheet2.getPivotTables();
// Adding a PivotTable to the worksheet
int index = pivotTables.add("=Data!A1:F30", "B3", "PivotTable1");
// Accessing the instance of the newly added PivotTable
PivotTable pivotTable = pivotTables.get(index);
// Showing the grand totals
pivotTable.setRowGrand(true);
pivotTable.setColumnGrand(true);
// Setting the PivotTable report is automatically formatted
pivotTable.setAutoFormat(true);
// Setting the PivotTable autoformat type.
pivotTable.setAutoFormatType(PivotTableAutoFormatType.REPORT_6);
// Draging the first field to the row area.
pivotTable.addFieldToArea(PivotFieldType.ROW, 0);
// Draging the third field to the row area.
pivotTable.addFieldToArea(PivotFieldType.ROW, 2);
// Draging the second field to the row area.
pivotTable.addFieldToArea(PivotFieldType.ROW, 1);
// Draging the fourth field to the column area.
pivotTable.addFieldToArea(PivotFieldType.COLUMN, 3);
// Draging the fifth field to the data area.
pivotTable.addFieldToArea(PivotFieldType.DATA, 5);
// Setting the number format of the first data field
pivotTable.getDataFields().get(0).setNumber(7);
// Saving the Excel file
workbook.save(dataDir + "pivotTable_test.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateScenariosfromWorksheets.class);
// Instantiate the Workbook
// Load an Excel file
Workbook workbook = new Workbook(dataDir + "Bk_scenarios.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Remove the existing first scenario from the sheet
worksheet.getScenarios().removeAt(0);
// Create a scenario
int i = worksheet.getScenarios().add("MyScenario");
// Get the scenario
Scenario scenario = worksheet.getScenarios().get(i);
// Add comment to it
scenario.setComment("Test sceanrio is created.");
// Get the input cells for the scenario
ScenarioInputCellCollection sic = scenario.getInputCells();
// Add the scenario on B4 (as changing cell) with default value
sic.add(3, 1, "1100000");
// Save the Excel file.
workbook.save(dataDir + "outBk_scenarios1.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateSignatureLine.class);
// Create workbook object
Workbook workbook = new Workbook();
// Insert picture of your choice
int index = workbook.getWorksheets().get(0).getPictures().add(0, 0, "signature.jpg");
// Access picture and add signature line inside it
Picture pic = workbook.getWorksheets().get(0).getPictures().get(index);
// Create signature line object
SignatureLine s = new SignatureLine();
s.setSigner("Simon Zhao");
s.setTitle("Development Lead");
s.setEmail("Simon.Zhao@aspose.com");
// Assign the signature line object to Picture.SignatureLine property
pic.setSignatureLine(s);
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CreateStyleobjectusingCellsFactoryclass.class) + "articles/";
// Create a Style object using CellsFactory class
CellsFactory cf = new CellsFactory();
Style st = cf.createStyle();
// Set the Style fill color to Yellow
st.setPattern(BackgroundType.SOLID);
st.setForegroundColor(Color.getYellow());
// Create a workbook and set its default style using the created Style
// object
Workbook wb = new Workbook();
wb.setDefaultStyle(st);
// Save the workbook
wb.save(dataDir + "CreateStyleobject_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(CreateTableforRange.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Obtaining the reference of the newly added worksheet
int sheetIndex = workbook.getWorksheets().add();
Worksheet worksheet = workbook.getWorksheets().get(sheetIndex);
// Accessing the "A1" cell from the worksheet
Cell cell = worksheet.getCells().get("A1");
// Creating a range of cells based on cells Address.
Range range = worksheet.getCells().createRange("A1:F10");
// Specify a Style object for borders.
Style style = cell.getStyle();
// Setting the line style of the top border
style.setBorder(BorderType.TOP_BORDER, CellBorderType.THICK, Color.getBlack());
// Setting the line style of the bottom border
style.setBorder(BorderType.BOTTOM_BORDER, CellBorderType.THICK, Color.getBlack());
// Setting the line style of the left border
style.setBorder(BorderType.LEFT_BORDER, CellBorderType.THICK, Color.getBlack());
// Setting the line style of the right border
style.setBorder(BorderType.RIGHT_BORDER, CellBorderType.THICK, Color.getBlack());
Iterator cellArray = range.iterator();
while (cellArray.hasNext()) {
Cell temp = (Cell) cellArray.next();
// Saving the modified style to the cell.
temp.setStyle(style);
}
// Saving the Excel file
workbook.save(dataDir + "borders_out.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateTextBoxhavingdifferentLineAlignment.class);
// Create a workbook.
Workbook wb = new Workbook();
// Access first worksheet.
Worksheet ws = wb.getWorksheets().get(0);
// Add text box inside the sheet.
ws.getShapes().addShape(MsoDrawingType.TEXT_BOX, 2, 0, 2, 0, 80, 400);
// Access first shape which is a text box and set is text.
Shape shape = ws.getShapes().get(0);
shape.setText(
"Sign up for your free phone number.\nCall and text online for free.\nCall your friends and family.");
// Acccess the first paragraph and set its horizontal alignment to left.
TextParagraph p = shape.getTextBody().getTextParagraphs().get(0);
p.setAlignmentType(TextAlignmentType.LEFT);
// Acccess the second paragraph and set its horizontal alignment to
// center.
p = shape.getTextBody().getTextParagraphs().get(1);
p.setAlignmentType(TextAlignmentType.CENTER);
// Acccess the third paragraph and set its horizontal alignment to
// right.
p = shape.getTextBody().getTextParagraphs().get(2);
p.setAlignmentType(TextAlignmentType.RIGHT);
// Save the workbook in xlsx format.
wb.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateTransparentImage.class);
// Create workbook object from source file
Workbook wb = new Workbook(dataDir + "aspose-sample.xlsx");
// Apply different image or print options
ImageOrPrintOptions imgOption = new ImageOrPrintOptions();
imgOption.setImageFormat(ImageFormat.getPng());
imgOption.setHorizontalResolution(200);
imgOption.setVerticalResolution(200);
imgOption.setOnePagePerSheet(true);
// Apply transparency to the output image
imgOption.setTransparent(true);
// Create image after apply image or print options
SheetRender sr = new SheetRender(wb.getWorksheets().get(0), imgOption);
sr.toImage(0, dataDir + "output.png");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CreateWaterfallChart.class);
// Create an instance of Workbook
Workbook workbook = new Workbook();
// Retrieve the first Worksheet in Workbook
Worksheet worksheet = workbook.getWorksheets().get(0);
// Retrieve the Cells of the first Worksheet
Cells cells = worksheet.getCells();
// Input some data which chart will use as source
cells.get("A1").putValue("Previous Year");
cells.get("A2").putValue("January");
cells.get("A3").putValue("March");
cells.get("A4").putValue("August");
cells.get("A5").putValue("October");
cells.get("A6").putValue("Current Year");
cells.get("B1").putValue(8.5);
cells.get("B2").putValue(1.5);
cells.get("B3").putValue(7.5);
cells.get("B4").putValue(7.5);
cells.get("B5").putValue(8.5);
cells.get("B6").putValue(3.5);
cells.get("C1").putValue(1.5);
cells.get("C2").putValue(4.5);
cells.get("C3").putValue(3.5);
cells.get("C4").putValue(9.5);
cells.get("C5").putValue(7.5);
cells.get("C6").putValue(9.5);
// Add a Chart of type Line in same worksheet as of data
int idx = worksheet.getCharts().add(ChartType.LINE, 4, 4, 25, 13);
// Reterieve the Chart object
Chart chart = worksheet.getCharts().get(idx);
// Add Series
chart.getNSeries().add("$B$1:$C$6", true);
// Add Category Data
chart.getNSeries().setCategoryData("$A$1:$A$6");
// Series has Up Down Bars
chart.getNSeries().get(0).setHasUpDownBars(true);
// Set the colors of Up and Down Bars
chart.getNSeries().get(0).getUpBars().getArea().setForegroundColor(Color.getGreen());
chart.getNSeries().get(0).getDownBars().getArea().setForegroundColor(Color.getRed());
// Make both Series Lines invisible
chart.getNSeries().get(0).getBorder().setVisible(false);
chart.getNSeries().get(1).getBorder().setVisible(false);
// Set the Plot Area Formatting Automatic
chart.getPlotArea().getArea().setFormatting(FormattingType.AUTOMATIC);
// Delete the Legend
chart.getLegend().getLegendEntries().get(0).setDeleted(true);
chart.getLegend().getLegendEntries().get(1).setDeleted(true);
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CreatingStyle.class) + "articles/";
// Create a workbook.
Workbook workbook = new Workbook();
// Create a new style object.
Style style = workbook.createStyle();
// Set the number format.
style.setNumber(14);
// Set the font color to red color.
style.getFont().setColor(Color.getRed());
// Name the style.
style.setName("Date1");
// Get the first worksheet cells.
Cells cells = workbook.getWorksheets().get(0).getCells();
// Specify the style (described above) to A1 cell.
cells.get("A1").setStyle(style);
// Create a range (B1:D1).
Range range = cells.createRange("B1", "D1");
// Initialize styleflag object.
StyleFlag flag = new StyleFlag();
// Set all formatting attributes on.
flag.setAll(true);
// Apply the style (described above)to the range.
range.applyStyle(style, flag);
// Modify the style (described above) and change the font color from red to black.
style.getFont().setColor(Color.getBlack());
// Done! Since the named style (described above) has been set to a cell and range,the change would be Reflected(new
// modification is implemented) to cell(A1) and //range (B1:D1).
style.update();
// Save the excel file.
workbook.save(dataDir + "CreatingStyle_out.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
import java.util.ArrayList;
import com.aspose.cells.DateTime;
import com.aspose.cells.ICustomFunction;
public class CustomFunctionStaticValue implements ICustomFunction {
@Override
public Object calculateCustomFunction(String functionName, ArrayList paramsList, ArrayList contextObjects) {
return new Object[][] { new Object[] { new DateTime(2015, 6, 12, 10, 6, 30), 2 },
new Object[] { 3.0, "Test" } };
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CustomizingThemes.class);
// Define Color array (of 12 colors) for the Theme
Color[] carr = new Color[12];
carr[0] = Color.getAntiqueWhite(); // Background1
carr[1] = Color.getBrown(); // Text1
carr[2] = Color.getAliceBlue(); // Background2
carr[3] = Color.getYellow(); // Text2
carr[4] = Color.getYellowGreen(); // Accent1
carr[5] = Color.getRed(); // Accent2
carr[6] = Color.getPink(); // Accent3
carr[7] = Color.getPurple(); // Accent4
carr[8] = Color.getPaleGreen(); // Accent5
carr[9] = Color.getOrange(); // Accent6
carr[10] = Color.getGreen(); // Hyperlink
carr[11] = Color.getGray(); // Followed Hyperlink
// Instantiate a Workbook
// Open the spreadsheet file
Workbook workbook = new Workbook(dataDir + "book1.xlsx");
// Set the custom theme with specified colors
workbook.customTheme("CustomeTheme1", carr);
// Save as the excel file
workbook.save(dataDir + "CustomThemeColor.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CustomLabelsforSubtotals.class) + "articles/";
// Loads an existing spreadsheet containing some data
Workbook book = new Workbook(dataDir + "sample.xlsx");
// Assigns the GlobalizationSettings property of the WorkbookSettings
// class
// to the class created in first step
book.getSettings().setGlobalizationSettings(new CustomSettings());
// Accesses the 1st worksheet from the collection which contains data
// Data resides in the cell range A2:B9
Worksheet sheet = book.getWorksheets().get(0);
// Adds SubTotal of type Average to the worksheet
sheet.getCells().subtotal(CellArea.createCellArea("A2", "B9"), 0, ConsolidationFunction.AVERAGE, new int[] { 1 });
// Calculates Formulas
book.calculateFormula();
// Auto fits all columns
sheet.autoFitColumns();
// Saves the workbook on disc
book.save(dataDir + "CustomLabelsforSubtotals_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public String getTotalName(int functionType) {
switch (functionType) {
case ConsolidationFunction.AVERAGE:
return "AVG";
// Handle other cases
default:
return super.getTotalName(functionType);
}
}
public String getGrandTotalName(int functionType) {
switch (functionType) {
case ConsolidationFunction.AVERAGE:
return "GRAND AVG";
// Handle other cases
default:
return super.getGrandTotalName(functionType);
}
}
public String getOtherName()
{
String language = Locale.getDefault().getLanguage();
System.out.println(language);
switch (language)
{
case "en":
return "Other";
case "fr":
return "Autre";
case "de":
return "Andere";
//Handle other cases as per requirement
default:
return super.getOtherName();
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(CustomSliceOrSectorColorsPieChart.class);
// Create a workbook object from the template file
Workbook workbook = new Workbook();
// Access the first worksheet.
Worksheet worksheet = workbook.getWorksheets().get(0);
// Put the sample values used in a pie chart
worksheet.getCells().get("C3").putValue("India");
worksheet.getCells().get("C4").putValue("China");
worksheet.getCells().get("C5").putValue("United States");
worksheet.getCells().get("C6").putValue("Russia");
worksheet.getCells().get("C7").putValue("United Kingdom");
worksheet.getCells().get("C8").putValue("Others");
// Put the sample values used in a pie chart
worksheet.getCells().get("D2").putValue("% of world population");
worksheet.getCells().get("D3").putValue(25);
worksheet.getCells().get("D4").putValue(30);
worksheet.getCells().get("D5").putValue(10);
worksheet.getCells().get("D6").putValue(13);
worksheet.getCells().get("D7").putValue(9);
worksheet.getCells().get("D8").putValue(13);
// Create a pie chart with desired length and width
int pieIdx = worksheet.getCharts().add(ChartType.PIE, 1, 6, 15, 14);
// Access the pie chart
Chart pie = worksheet.getCharts().get(pieIdx);
// Set the pie chart series
pie.getNSeries().add("D3:D8", true);
// Set the category data
pie.getNSeries().setCategoryData("=Sheet1!$C$3:$C$8");
// Set the chart title that is linked to cell D2
pie.getTitle().setLinkedSource("D2");
// Set the legend position at the bottom.
pie.getLegend().setPosition(LegendPositionType.BOTTOM);
// Set the chart title's font name and color
pie.getTitle().getFont().setName("Calibri");
pie.getTitle().getFont().setSize(18);
// Access the chart series
Series srs = pie.getNSeries().get(0);
// Color the indvidual points with custom colors
srs.getPoints().get(0).getArea().setForegroundColor(com.aspose.cells.Color.fromArgb(0, 246, 22, 219));
srs.getPoints().get(1).getArea().setForegroundColor(com.aspose.cells.Color.fromArgb(0, 51, 34, 84));
srs.getPoints().get(2).getArea().setForegroundColor(com.aspose.cells.Color.fromArgb(0, 46, 74, 44));
srs.getPoints().get(3).getArea().setForegroundColor(com.aspose.cells.Color.fromArgb(0, 19, 99, 44));
srs.getPoints().get(4).getArea().setForegroundColor(com.aspose.cells.Color.fromArgb(0, 208, 223, 7));
srs.getPoints().get(5).getArea().setForegroundColor(com.aspose.cells.Color.fromArgb(0, 222, 69, 8));
// Autofit all columns
worksheet.autoFitColumns();
// Save the workbook
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(CustomTextforOtherLabelofPieChart.class) + "articles/";
//Loads an existing spreadsheet containing a pie chart
Workbook book = new Workbook(dataDir + "sample.xlsx");
//Assigns the GlobalizationSettings property of the WorkbookSettings class
//to the class created in first step
book.getSettings().setGlobalizationSettings(new CustomSettings());
//Accesses the 1st worksheet from the collection which contains pie chart
Worksheet sheet = book.getWorksheets().get(0);
//Accesses the 1st chart from the collection
Chart chart = sheet.getCharts().get(0);
//Refreshes the chart
chart.calculate();
//Renders the chart to image
chart.toImage(dataDir + "CustomTextforOtherLabelofPieChart_out.png", new ImageOrPrintOptions());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DataFormatting.class);
// Create a new Workbook.
Workbook workbook = new Workbook();
// Obtain the cells of the first worksheet.
Cells cells = workbook.getWorksheets().get(0).getCells();
// Input the title on B1 cell.
cells.get("B1").putValue("Western Product Sales 2006");
// Insert some column headings in the second row.
Cell cell = cells.get("B2");
cell.putValue("January");
cell = cells.get("C2");
cell.putValue("February");
cell = cells.get("D2");
cell.putValue("March");
cell = cells.get("E2");
cell.putValue("April");
cell = cells.get("F2");
cell.putValue("May");
cell = cells.get("G2");
cell.putValue("June");
cell = cells.get("H2");
cell.putValue("July");
cell = cells.get("I2");
cell.putValue("August");
cell = cells.get("J2");
cell.putValue("September");
cell = cells.get("K2");
cell.putValue("October");
cell = cells.get("L2");
cell.putValue("November");
cell = cells.get("M2");
cell.putValue("December");
cell = cells.get("N2");
cell.putValue("Total");
// Insert product names.
cells.get("A3").putValue("Biscuits");
cells.get("A4").putValue("Coffee");
cells.get("A5").putValue("Tofu");
cells.get("A6").putValue("Ikura");
cells.get("A7").putValue("Choclade");
cells.get("A8").putValue("Maxilaku");
cells.get("A9").putValue("Scones");
cells.get("A10").putValue("Sauce");
cells.get("A11").putValue("Syrup");
cells.get("A12").putValue("Spegesild");
cells.get("A13").putValue("Filo Mix");
cells.get("A14").putValue("Pears");
cells.get("A15").putValue("Konbu");
cells.get("A16").putValue("Kaviar");
cells.get("A17").putValue("Zaanse");
cells.get("A18").putValue("Cabrales");
cells.get("A19").putValue("Gnocchi");
cells.get("A20").putValue("Wimmers");
cells.get("A21").putValue("Breads");
cells.get("A22").putValue("Lager");
cells.get("A23").putValue("Gravad");
cells.get("A24").putValue("Telino");
cells.get("A25").putValue("Pavlova");
cells.get("A26").putValue("Total");
// Input porduct sales data (B3:M25).
cells.get("B3").putValue(5000);
cells.get("C3").putValue(4500);
cells.get("D3").putValue(6010);
cells.get("E3").putValue(7230);
cells.get("F3").putValue(5400);
cells.get("G3").putValue(5030);
cells.get("H3").putValue(3000);
cells.get("I3").putValue(6000);
cells.get("J3").putValue(9000);
cells.get("K3").putValue(3300);
cells.get("L3").putValue(2500);
cells.get("M3").putValue(5510);
cells.get("B4").putValue(4000);
cells.get("C4").putValue(2500);
cells.get("D4").putValue(6000);
cells.get("E4").putValue(5300);
cells.get("F4").putValue(7400);
cells.get("G4").putValue(7030);
cells.get("H4").putValue(4000);
cells.get("I4").putValue(4000);
cells.get("J4").putValue(5500);
cells.get("K4").putValue(4500);
cells.get("L4").putValue(2500);
cells.get("M4").putValue(2510);
cells.get("B5").putValue(2000);
cells.get("C5").putValue(1500);
cells.get("D5").putValue(3000);
cells.get("E5").putValue(2500);
cells.get("F5").putValue(3400);
cells.get("G5").putValue(4030);
cells.get("H5").putValue(2000);
cells.get("I5").putValue(2000);
cells.get("J5").putValue(1500);
cells.get("K5").putValue(2200);
cells.get("L5").putValue(2100);
cells.get("M5").putValue(2310);
cells.get("B6").putValue(1000);
cells.get("C6").putValue(1300);
cells.get("D6").putValue(2000);
cells.get("E6").putValue(2600);
cells.get("F6").putValue(5400);
cells.get("G6").putValue(2030);
cells.get("H6").putValue(2100);
cells.get("I6").putValue(4000);
cells.get("J6").putValue(6500);
cells.get("K6").putValue(5600);
cells.get("L6").putValue(3300);
cells.get("M6").putValue(5110);
cells.get("B7").putValue(3000);
cells.get("C7").putValue(3500);
cells.get("D7").putValue(1000);
cells.get("E7").putValue(4500);
cells.get("F7").putValue(5400);
cells.get("G7").putValue(2030);
cells.get("H7").putValue(3000);
cells.get("I7").putValue(3000);
cells.get("J7").putValue(4500);
cells.get("K7").putValue(6000);
cells.get("L7").putValue(3000);
cells.get("M7").putValue(3000);
cells.get("B8").putValue(5000);
cells.get("C8").putValue(5500);
cells.get("D8").putValue(5000);
cells.get("E8").putValue(5500);
cells.get("F8").putValue(5400);
cells.get("G8").putValue(5030);
cells.get("H8").putValue(5000);
cells.get("I8").putValue(2500);
cells.get("J8").putValue(5500);
cells.get("K8").putValue(5200);
cells.get("L8").putValue(5500);
cells.get("M8").putValue(2510);
cells.get("B9").putValue(4100);
cells.get("C9").putValue(1500);
cells.get("D9").putValue(1000);
cells.get("E9").putValue(2300);
cells.get("F9").putValue(3300);
cells.get("G9").putValue(4030);
cells.get("H9").putValue(5000);
cells.get("I9").putValue(6000);
cells.get("J9").putValue(3500);
cells.get("K9").putValue(4300);
cells.get("L9").putValue(2300);
cells.get("M9").putValue(2110);
cells.get("B10").putValue(2000);
cells.get("C10").putValue(2300);
cells.get("D10").putValue(3000);
cells.get("E10").putValue(3300);
cells.get("F10").putValue(3400);
cells.get("G10").putValue(3030);
cells.get("H10").putValue(3000);
cells.get("I10").putValue(3000);
cells.get("J10").putValue(3500);
cells.get("K10").putValue(3500);
cells.get("L10").putValue(3500);
cells.get("M10").putValue(3510);
cells.get("B11").putValue(4400);
cells.get("C11").putValue(4500);
cells.get("D11").putValue(4000);
cells.get("E11").putValue(4300);
cells.get("F11").putValue(4400);
cells.get("G11").putValue(4030);
cells.get("H11").putValue(5000);
cells.get("I11").putValue(5000);
cells.get("J11").putValue(4500);
cells.get("K11").putValue(4400);
cells.get("L11").putValue(4400);
cells.get("M11").putValue(4510);
cells.get("B12").putValue(2000);
cells.get("C12").putValue(1500);
cells.get("D12").putValue(3000);
cells.get("E12").putValue(2300);
cells.get("F12").putValue(3400);
cells.get("G12").putValue(3030);
cells.get("H12").putValue(3000);
cells.get("I12").putValue(3000);
cells.get("J12").putValue(2500);
cells.get("K12").putValue(2500);
cells.get("L12").putValue(1500);
cells.get("M12").putValue(5110);
cells.get("B13").putValue(4000);
cells.get("C13").putValue(1400);
cells.get("D13").putValue(1400);
cells.get("E13").putValue(3300);
cells.get("F13").putValue(3300);
cells.get("G13").putValue(3730);
cells.get("H13").putValue(3800);
cells.get("I13").putValue(3600);
cells.get("J13").putValue(2600);
cells.get("K13").putValue(4600);
cells.get("L13").putValue(1400);
cells.get("M13").putValue(2660);
cells.get("B14").putValue(3000);
cells.get("C14").putValue(3500);
cells.get("D14").putValue(3333);
cells.get("E14").putValue(2330);
cells.get("F14").putValue(3430);
cells.get("G14").putValue(3040);
cells.get("H14").putValue(3040);
cells.get("I14").putValue(3030);
cells.get("J14").putValue(1509);
cells.get("K14").putValue(4503);
cells.get("L14").putValue(1503);
cells.get("M14").putValue(3113);
cells.get("B15").putValue(2010);
cells.get("C15").putValue(1520);
cells.get("D15").putValue(3030);
cells.get("E15").putValue(2320);
cells.get("F15").putValue(3410);
cells.get("G15").putValue(3000);
cells.get("H15").putValue(3000);
cells.get("I15").putValue(3020);
cells.get("J15").putValue(2520);
cells.get("K15").putValue(2520);
cells.get("L15").putValue(1520);
cells.get("M15").putValue(5120);
cells.get("B16").putValue(2220);
cells.get("C16").putValue(1200);
cells.get("D16").putValue(3220);
cells.get("E16").putValue(1320);
cells.get("F16").putValue(1400);
cells.get("G16").putValue(1030);
cells.get("H16").putValue(3200);
cells.get("I16").putValue(3020);
cells.get("J16").putValue(2100);
cells.get("K16").putValue(2100);
cells.get("L16").putValue(1100);
cells.get("M16").putValue(5210);
cells.get("B17").putValue(1444);
cells.get("C17").putValue(1540);
cells.get("D17").putValue(3040);
cells.get("E17").putValue(2340);
cells.get("F17").putValue(1440);
cells.get("G17").putValue(1030);
cells.get("H17").putValue(3000);
cells.get("I17").putValue(4000);
cells.get("J17").putValue(4500);
cells.get("K17").putValue(2500);
cells.get("L17").putValue(4500);
cells.get("M17").putValue(5550);
cells.get("B18").putValue(4000);
cells.get("C18").putValue(5500);
cells.get("D18").putValue(3000);
cells.get("E18").putValue(3300);
cells.get("F18").putValue(3330);
cells.get("G18").putValue(5330);
cells.get("H18").putValue(3400);
cells.get("I18").putValue(3040);
cells.get("J18").putValue(2540);
cells.get("K18").putValue(4500);
cells.get("L18").putValue(4500);
cells.get("M18").putValue(2110);
cells.get("B19").putValue(2000);
cells.get("C19").putValue(2500);
cells.get("D19").putValue(3200);
cells.get("E19").putValue(3200);
cells.get("F19").putValue(2330);
cells.get("G19").putValue(5230);
cells.get("H19").putValue(2400);
cells.get("I19").putValue(3240);
cells.get("J19").putValue(2240);
cells.get("K19").putValue(4300);
cells.get("L19").putValue(4100);
cells.get("M19").putValue(2310);
cells.get("B20").putValue(7000);
cells.get("C20").putValue(8500);
cells.get("D20").putValue(8000);
cells.get("E20").putValue(5300);
cells.get("F20").putValue(6330);
cells.get("G20").putValue(7330);
cells.get("H20").putValue(3600);
cells.get("I20").putValue(3940);
cells.get("J20").putValue(2940);
cells.get("K20").putValue(4600);
cells.get("L20").putValue(6500);
cells.get("M20").putValue(8710);
cells.get("B21").putValue(4000);
cells.get("C21").putValue(4500);
cells.get("D21").putValue(2000);
cells.get("E21").putValue(2200);
cells.get("F21").putValue(2000);
cells.get("G21").putValue(3000);
cells.get("H21").putValue(3000);
cells.get("I21").putValue(3000);
cells.get("J21").putValue(4330);
cells.get("K21").putValue(4420);
cells.get("L21").putValue(4500);
cells.get("M21").putValue(1330);
cells.get("B22").putValue(2050);
cells.get("C22").putValue(3520);
cells.get("D22").putValue(1030);
cells.get("E22").putValue(2000);
cells.get("F22").putValue(3000);
cells.get("G22").putValue(2000);
cells.get("H22").putValue(2010);
cells.get("I22").putValue(2210);
cells.get("J22").putValue(2230);
cells.get("K22").putValue(4240);
cells.get("L22").putValue(3330);
cells.get("M22").putValue(2000);
cells.get("B23").putValue(1222);
cells.get("C23").putValue(3000);
cells.get("D23").putValue(3020);
cells.get("E23").putValue(2770);
cells.get("F23").putValue(3011);
cells.get("G23").putValue(2000);
cells.get("H23").putValue(6000);
cells.get("I23").putValue(9000);
cells.get("J23").putValue(4000);
cells.get("K23").putValue(2000);
cells.get("L23").putValue(5000);
cells.get("M23").putValue(6333);
cells.get("B24").putValue(1000);
cells.get("C24").putValue(2000);
cells.get("D24").putValue(1000);
cells.get("E24").putValue(1300);
cells.get("F24").putValue(1330);
cells.get("G24").putValue(1390);
cells.get("H24").putValue(1600);
cells.get("I24").putValue(1900);
cells.get("J24").putValue(1400);
cells.get("K24").putValue(1650);
cells.get("L24").putValue(1520);
cells.get("M24").putValue(1910);
cells.get("B25").putValue(2000);
cells.get("C25").putValue(6600);
cells.get("D25").putValue(3300);
cells.get("E25").putValue(8300);
cells.get("F25").putValue(2000);
cells.get("G25").putValue(3000);
cells.get("H25").putValue(6000);
cells.get("I25").putValue(4000);
cells.get("J25").putValue(7000);
cells.get("K25").putValue(2000);
cells.get("L25").putValue(5000);
cells.get("M25").putValue(5500);
// Add Month wise Summary formulas.
cells.get("B26").setFormula("=SUM(B3:B25)");
cells.get("C26").setFormula("=SUM(C3:C25)");
cells.get("D26").setFormula("=SUM(D3:D25)");
cells.get("E26").setFormula("=SUM(E3:E25)");
cells.get("F26").setFormula("=SUM(F3:F25)");
cells.get("G26").setFormula("=SUM(G3:G25)");
cells.get("H26").setFormula("=SUM(H3:H25)");
cells.get("I26").setFormula("=SUM(I3:I25)");
cells.get("J26").setFormula("=SUM(J3:J25)");
cells.get("K26").setFormula("=SUM(K3:K25)");
cells.get("L26").setFormula("=SUM(L3:L25)");
cells.get("M26").setFormula("=SUM(M3:M25)");
// Add Product wise Summary formulas.
cells.get("N3").setFormula("=SUM(B3:M3)");
cells.get("N4").setFormula("=SUM(B4:M4)");
cells.get("N5").setFormula("=SUM(B5:M5)");
cells.get("N6").setFormula("=SUM(B6:M6)");
cells.get("N7").setFormula("=SUM(B7:M7)");
cells.get("N8").setFormula("=SUM(B8:M8)");
cells.get("N9").setFormula("=SUM(B9:M9)");
cells.get("N10").setFormula("=SUM(B10:M10)");
cells.get("N11").setFormula("=SUM(B11:M11)");
cells.get("N12").setFormula("=SUM(B12:M12)");
cells.get("N13").setFormula("=SUM(B13:M13)");
cells.get("N14").setFormula("=SUM(B14:M14)");
cells.get("N15").setFormula("=SUM(B15:M15)");
cells.get("N16").setFormula("=SUM(B16:M16)");
cells.get("N17").setFormula("=SUM(B17:M17)");
cells.get("N18").setFormula("=SUM(B18:M18)");
cells.get("N19").setFormula("=SUM(B19:M19)");
cells.get("N20").setFormula("=SUM(B20:M20)");
cells.get("N21").setFormula("=SUM(B21:M21)");
cells.get("N22").setFormula("=SUM(B22:M22)");
cells.get("N23").setFormula("=SUM(B23:M23)");
cells.get("N24").setFormula("=SUM(B24:M24)");
cells.get("N25").setFormula("=SUM(B25:M25)");
// Add Grand Total.
cells.get("N26").setFormula("=SUM(N3:N25)");
// Define a style object
Style stl0 = workbook.createStyle();
// Set a custom shading color of the cells.
stl0.setForegroundColor(Color.fromArgb(155, 204, 255));
// Set the solid background fill.
stl0.setPattern(BackgroundType.SOLID);
// Set a font.
stl0.getFont().setName("Trebuchet MS");
// Set the size.
stl0.getFont().setSize(18);
// Set the font text color.
stl0.getFont().setColor(Color.getMaroon());
// Set it bold
stl0.getFont().setBold(true);
// Set it italic.
stl0.getFont().setItalic(true);
// Define a style flag struct.
StyleFlag flag = new StyleFlag();
// Apply cell shading.
flag.setCellShading(true);
// Apply font.
flag.setFontName(true);
// Apply font size.
flag.setFontSize(true);
// Apply font color.
flag.setFontColor(true);
// Apply bold font.
flag.setFontBold(true);
// Apply italic attribute.
flag.setFontItalic(true);
// Get the first row in the first worksheet.
Row row = workbook.getWorksheets().get(0).getCells().getRows().get(0);
// Apply the style to it.
row.applyStyle(stl0, flag);
// Obtain the cells of the first worksheet.
cells = workbook.getWorksheets().get(0).getCells();
// Set the height of the first row.
cells.setRowHeight(0, 30);
// Define a style object adding a new style
// to the collection list.
Style stl1 = workbook.createStyle();
// Set the rotation angle of the text.
stl1.setRotationAngle(45);
// Set the custom fill color of the cells.
stl1.setForegroundColor(Color.fromArgb(0, 51, 105));
// Set the solid background pattern for fill.
stl1.setPattern(BackgroundType.SOLID);
// Set the left border line style.
stl1.getBorders().getByBorderType(BorderType.LEFT_BORDER).setLineStyle(CellBorderType.THIN);
// Set the left border line color.
stl1.getBorders().getByBorderType(BorderType.LEFT_BORDER).setColor(Color.getWhite());
// Set the horizontal alignment to center aligned.
stl1.setHorizontalAlignment(TextAlignmentType.CENTER);
// Set the vertical alignment to center aligned.
stl1.setVerticalAlignment(TextAlignmentType.CENTER);
// Set the font.
stl1.getFont().setName("Times New Roman");
// Set the font size.
stl1.getFont().setSize(10);
// Set the font color.
stl1.getFont().setColor(Color.getWhite());
// Set the bold attribute.
stl1.getFont().setBold(true);
// Set the style flag struct.
flag = new StyleFlag();
// Apply the left border.
flag.setLeftBorder(true);
// Apply text rotation orientation.
flag.setRotation(true);
// Apply fill color of cells.
flag.setCellShading(true);
// Apply horizontal alignment.
flag.setHorizontalAlignment(true);
// Apply vertical alignment.
flag.setVerticalAlignment(true);
// Apply the font.
flag.setFontName(true);
// Apply the font size.
flag.setFontSize(true);
// Apply the font color.
flag.setFontColor(true);
// Apply the bold attribute.
flag.setFontBold(true);
// Get the second row of the first worksheet.
row = workbook.getWorksheets().get(0).getCells().getRows().get(1);
// Apply the style to it.
row.applyStyle(stl1, flag);
// Set the height of the second row.
cells.setRowHeight(1, 48);
// Define a style object adding a new style
// to the collection list.
Style stl2 = workbook.createStyle();
// Set the custom cell shading color.
stl2.setForegroundColor(Color.fromArgb(155, 204, 255));
// Set the solid background pattern for fill color.
stl2.setPattern(BackgroundType.SOLID);
// Set the font.
stl2.getFont().setName("Trebuchet MS");
// Set the font color.
stl2.getFont().setColor(Color.getMaroon());
// Set the font size.
stl2.getFont().setSize(10);
// Set the style flag struct.
flag = new StyleFlag();
// Apply cell shading.
flag.setCellShading(true);
// Apply the font.
flag.setFontName(true);
// Apply the font color.
flag.setFontColor(true);
// Apply the font size.
flag.setFontSize(true);
// Get the first column in the first worksheet.
Column col = workbook.getWorksheets().get(0).getCells().getColumns().get(0);
// Apply the style to it.
col.applyStyle(stl2, flag);
// Define a style object adding a new style
// to the collection list.
Style stl3 = workbook.createStyle();
// Set the custom cell filling color.
stl3.setForegroundColor(Color.fromArgb(124, 199, 72));
// Set the solid background pattern for fill color.
stl3.setPattern(BackgroundType.SOLID);
// Apply the style to A2 cell.
cells.get("A2").setStyle(stl3);
// Define a style object adding a new style
// to the collection list.
Style stl4 = workbook.createStyle();
// Set the custom font text color.
stl4.getFont().setColor(Color.fromArgb(0, 51, 105));
// Set the bottom border line style.
stl4.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setLineStyle(CellBorderType.THIN);
// Set the bottom border line color to custom color.
stl4.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setColor(Color.fromArgb(124, 199, 72));
// Set the background fill color of the cells.
stl4.setForegroundColor(Color.getWhite());
// Set the solid fill color pattern.
stl4.setPattern(BackgroundType.SOLID);
// Set custom number format.
stl4.setCustom("$#,##0.0");
// Set a style flag struct.
flag = new StyleFlag();
// Apply font color.
flag.setFontColor(true);
// Apply cell shading color.
flag.setCellShading(true);
// Apply custom number format.
flag.setNumberFormat(true);
// Apply bottom border.
flag.setBottomBorder(true);
// Define a style object adding a new style
// to the collection list.
Style stl5 = workbook.createStyle();
// Set the bottom borde line style.
stl5.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setLineStyle(CellBorderType.THIN);
// Set the bottom border line color.
stl5.getBorders().getByBorderType(BorderType.BOTTOM_BORDER).setColor(Color.fromArgb(124, 199, 72));
// Set the custom shading color of the cells.
stl5.setForegroundColor(Color.fromArgb(250, 250, 200));
// Set the solid background pattern for fillment color.
stl5.setPattern(BackgroundType.SOLID);
// Set custom number format.
stl5.setCustom("$#,##0.0");
// Set font text color.
stl5.getFont().setColor(Color.getMaroon());
// Create a named range of cells (B3:M25)in the first worksheet.
Range range = workbook.getWorksheets().get(0).getCells().createRange("B3", "M25");
// Name the range.
range.setName("MyRange");
// Apply the style to cells in the named range.
range.applyStyle(stl4, flag);
// Apply different style to alternative rows
// in the range.
for (int i = 0; i <= 22; i++) {
for (int j = 0; j < 12; j++) {
if (i % 2 == 0) {
range.get(i, j).setStyle(stl5);
}
}
}
// Define a style object adding a new style
// to the collection list.
Style stl6 = workbook.createStyle();
// Set the custom fill color of the cells.
stl6.setForegroundColor(Color.fromArgb(0, 51, 105));
// Set the background pattern for fill color.
stl6.setPattern(BackgroundType.SOLID);
// Set the font.
stl6.getFont().setName("Arial");
// Set the font size.
stl6.getFont().setSize(10);
// Set the font color
stl6.getFont().setColor(Color.getWhite());
// Set the text bold.
stl6.getFont().setBold(true);
// Set the custom number format.
stl6.setCustom("$#,##0.0");
// Set the style flag struct.
flag = new StyleFlag();
// Apply cell shading.
flag.setCellShading(true);
// Apply the arial font.
flag.setFontName(true);
// Apply the font size.
flag.setFontSize(true);
// Apply the font color.
flag.setFontColor(true);
// Apply the bold attribute.
flag.setFontBold(true);
// Apply the number format.
flag.setNumberFormat(true);
// Get the 26th row in the first worksheet which produces totals.
row = workbook.getWorksheets().get(0).getCells().getRows().get(25);
// Apply the style to it.
row.applyStyle(stl6, flag);
// Now apply this style to those cells (N3:N25) which
// has product wise sales totals.
for (int i = 2; i < 25; i++) {
cells.get(1, 13).setStyle(stl6);
}
// Set N column's width to fit the contents.
workbook.getWorksheets().get(0).getCells().setColumnWidth(13, 9.33);
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public static void main(String[] args) throws Exception {
// Test calculation time after setting recursive true
TestCalcTimeRecursive(true);
// Test calculation time after setting recursive false
TestCalcTimeRecursive(false);
}
// --------------------------------------------------
static void TestCalcTimeRecursive(boolean rec) throws Exception {
String dataDir = Utils.getDataDir(DecreaseCalculationTime.class);
// Load your sample workbook
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Set the calculation option, set recursive true or false as per parameter
CalculationOptions opts = new CalculationOptions();
opts.setRecursive(rec);
// Start calculating time in nanoseconds
long startTime = System.nanoTime();
// Calculate cell A1 one million times
for (int i = 0; i < 1000000; i++) {
ws.getCells().get("A1").calculate(opts);
}
// Calculate elapsed time in seconds
long second = 1000000000;
long estimatedTime = System.nanoTime() - startTime;
estimatedTime = estimatedTime / second;
// Print the elapsed time in seconds
System.out.println("Recursive " + rec + ": " + estimatedTime + " seconds");
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DeletePivotTableFromWorksheet.class);
// Create workbook object from source Excel file
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the first pivot table object
PivotTable pivotTable = worksheet.getPivotTables().get(0);
// Remove pivot table using pivot table object
worksheet.getPivotTables().remove(pivotTable);
// Remove pivot table using pivot table position
worksheet.getPivotTables().removeAt(0);
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory
String dataDir = Utils.getDataDir(DeleteRedundantSpacesFromHtml.class);
// Sample Html containing redundant spaces after <br> tag
String html = "<html>" + "<body>" + "<table>" + "<tr>" + "<td>" + "<br> This is sample data"
+ "<br> This is sample data" + "<br> This is sample data" + "</td>" + "</tr>" + "</table>"
+ "</body>" + "</html>";
// Convert Html to byte array
byte[] byteArray = html.getBytes();
// Set Html load options and keep precision true
HTMLLoadOptions loadOptions = new HTMLLoadOptions(LoadFormat.HTML);
loadOptions.setDeleteRedundantSpaces(true);
// Convert byte array into stream
java.io.ByteArrayInputStream stream = new java.io.ByteArrayInputStream(byteArray);
// Create workbook from stream with Html load options
Workbook workbook = new Workbook(stream, loadOptions);
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Auto fit the sheet columns
worksheet.autoFitColumns();
// Save the workbook
workbook.save(dataDir + "output-" + loadOptions.getDeleteRedundantSpaces() + ".xlsx", SaveFormat.XLSX);
System.out.println("File saved");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DeletingBlankColumns.class);
// Create a new Workbook. Open an existing excel file.
Workbook wb = new Workbook(dataDir + "Book1.xlsx");
// Create a Worksheets object with reference to the sheets of the Workbook.
WorksheetCollection sheets = wb.getWorksheets();
// Get first Worksheet from WorksheetCollection
Worksheet sheet = sheets.get(0);
// Delete the Blank Columns from the worksheet
sheet.getCells().deleteBlankColumns();
// Save the excel file.
wb.save(dataDir + "Output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DeletingBlankRows.class);
// Create a new Workbook. Open an existing excel file.
Workbook wb = new Workbook(dataDir + "Book1.xlsx");
// Create a Worksheets object with reference to the sheets of the Workbook.
WorksheetCollection sheets = wb.getWorksheets();
// Get first Worksheet from WorksheetCollection
Worksheet sheet = sheets.get(0);
// Delete the Blank Rows from the worksheet
sheet.getCells().deleteBlankRows();
// Save the excel file.
wb.save(dataDir + "Output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class Demo {
private static final String OUTPUT_FILE_PATH = Utils.getDataDir(LightCellsDataProviderDemo.class);
public static void main(String[] args) throws Exception {
// Instantiate a new Workbook
Workbook wb = new Workbook();
// set the sheet count
int sheetCount = 1;
// set the number of rows for the big matrix
int rowCount = 100000;
// specify the worksheet
for (int k = 0; k < sheetCount; k++) {
Worksheet sheet = null;
if (k == 0) {
sheet = wb.getWorksheets().get(k);
sheet.setName("test");
} else {
int sheetIndex = wb.getWorksheets().add();
sheet = wb.getWorksheets().get(sheetIndex);
sheet.setName("test" + sheetIndex);
}
Cells cells = sheet.getCells();
// set the columns width
for (int j = 0; j < 15; j++) {
cells.setColumnWidth(j, 15);
}
// traverse the columns for adding hyperlinks and merging
for (int i = 0; i < rowCount; i++) {
// The first 10 columns
for (int j = 0; j < 10; j++) {
if (j % 3 == 0) {
cells.merge(i, j, 1, 2, false, false);
}
if (i % 50 == 0) {
if (j == 0) {
sheet.getHyperlinks().add(i, j, 1, 1, "test!A1");
} else if (j == 3) {
sheet.getHyperlinks().add(i, j, 1, 1, "http://www.google.com");
}
}
}
// The second 10 columns
for (int j = 10; j < 20; j++) {
if (j == 12) {
cells.merge(i, j, 1, 3, false, false);
}
}
}
}
// Create an object with respect to LightCells data provider
LightCellsDataProviderDemo dataProvider = new LightCellsDataProviderDemo(wb, 1, rowCount, 20);
// Specify the XLSX file's Save options
OoxmlSaveOptions opt = new OoxmlSaveOptions();
// Set the data provider for the file
opt.setLightCellsDataProvider(dataProvider);
// Save the big file
wb.save(OUTPUT_FILE_PATH + "/DemoTest.xlsx", opt);
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Create an instance of workbook
Workbook workbook = new Workbook();
// Access first worksheet from the collection
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access cells A1 and A2
Cell a1 = worksheet.getCells().get("A1");
Cell a2 = worksheet.getCells().get("A2");
// Add simple text to cell A1 and text with quote prefix to cell A2
a1.putValue("sample");
a2.putValue("'sample");
// Print their string values, A1 and A2 both are same
System.out.println("String value of A1: " + a1.getStringValue());
System.out.println("String value of A2: " + a2.getStringValue());
// Access styles of cells A1 and A2
Style s1 = a1.getStyle();
Style s2 = a2.getStyle();
System.out.println();
// Check if A1 and A2 has a quote prefix
System.out.println("A1 has a quote prefix: " + s1.getQuotePrefix());
System.out.println("A2 has a quote prefix: " + s2.getQuotePrefix());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DetectFileFormatandCheckFileEncrypted.class);
// Detect file format
FileFormatInfo info = FileFormatUtil.detectFileFormat(dataDir + "Book1.xlsx");
// Gets the detected load format
System.out.println("The spreadsheet format is: " + FileFormatUtil.loadFormatToExtension(info.getLoadFormat()));
// Check if the file is encrypted.
System.out.println("The file is encrypted: " + info.isEncrypted());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DetectMergedCells.class);
// Instantiate a new Workbook
Workbook wkBook = new Workbook(dataDir + "MergeTrial.xls");
// Get a worksheet in the workbook
Worksheet wkSheet = wkBook.getWorksheets().get("Merge Trial");
// Clear its contents
wkSheet.getCells().clearContents(0, 0, wkSheet.getCells().getMaxDataRow(),
wkSheet.getCells().getMaxDataColumn());
// Create an arraylist object, Get the merged cells list to put it into the arraylist object
ArrayList<CellArea> al = wkSheet.getCells().getMergedCells();
// Define cellarea
CellArea ca;
// Define some variables
int frow, fcol, erow, ecol;
// Loop through the arraylist and get each cellarea to unmerge it
for (int i = al.size() - 1; i > -1; i--) {
ca = new CellArea();
ca = (CellArea) al.get(i);
frow = ca.StartRow;
fcol = ca.StartColumn;
erow = ca.EndRow;
ecol = ca.EndColumn;
wkSheet.getCells().unMerge(frow, fcol, erow, ecol);
}
// Save the excel file
wkBook.save(dataDir + "output_MergeTrial.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DetectWorksheetisPasswordProtected.class);
// Create an instance of Workbook and load a spreadsheet
Workbook book = new Workbook(dataDir + "sample.xlsx");
// Access the protected Worksheet
Worksheet sheet = book.getWorksheets().get(0);
// Check if Worksheet is password protected
if (sheet.getProtection().isProtectedWithPassword()) {
System.out.println("Worksheet is password protected");
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DeterminetheLicenseLoadedSuccessfully.class);
// Create workbook object before setting a license
Workbook workbook = new Workbook();
// Check if the license is loaded or not
// It will return false
System.out.println(workbook.isLicensed());
// Set the license now
String licPath = dataDir + "Aspose.Total.lic";
com.aspose.cells.License lic = new com.aspose.cells.License();
lic.setLicense(licPath);
// Check if the license is loaded or not
// Now it will return true
System.out.println(workbook.isLicensed());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DetermineWhichAxisExistsInChart.class);
// Create workbook object
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the chart
Chart chart = worksheet.getCharts().get(0);
// Determine which axis exists in chart
boolean ret = chart.hasAxis(AxisType.CATEGORY, true);
System.out.println("Has Primary Category Axis: " + ret);
ret = chart.hasAxis(AxisType.CATEGORY, false);
System.out.println("Has Secondary Category Axis: " + ret);
ret = chart.hasAxis(AxisType.VALUE, true);
System.out.println("Has Primary Value Axis: " + ret);
ret = chart.hasAxis(AxisType.VALUE, false);
System.out.println("Has Seconary Value Axis: " + ret);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DisableCompatibilityChecker.class);
// Open a template file
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
// Disable the compatibility checker
workbook.getSettings().setCheckCompatibility(false);
// Saving the Excel file
workbook.save(dataDir + "outCompCheck.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DisableExporting.class);
// Open the required workbook to convert
Workbook w = new Workbook(dataDir + "Sample1.xlsx");
// Disable exporting frame scripts and document properties
HtmlSaveOptions options = new HtmlSaveOptions();
options.setExportFrameScriptsAndProperties(false);
// Save workbook as HTML
w.save(dataDir + "output.html", options);
System.out.println("File saved");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DisableTextWrapping.class);
// Load the sample Excel file inside the workbook object
Workbook workbook = new Workbook(dataDir + "SampleChart.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the first chart inside the worksheet
Chart chart = worksheet.getCharts().get(0);
// Disable the Text Wrapping of Data Labels in all Series
chart.getNSeries().get(0).getDataLabels().setTextWrapped(false);
chart.getNSeries().get(1).getDataLabels().setTextWrapped(false);
chart.getNSeries().get(2).getDataLabels().setTextWrapped(false);
// Save the workbook
workbook.save(dataDir + "Output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(DisplayBullets.class);
//Create workbook object
Workbook workbook = new Workbook();
//Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
//Access cell A1
Cell cell = worksheet.getCells().get("A1");
//Set the HTML string
cell.setHtmlString("<font style='font-family:Arial;font-size:10pt;color:#666666;vertical-align:top;text-align:left;'>Text 1 </font><font style='font-family:Wingdings;font-size:8.0pt;color:#009DD9;mso-font-charset:2;'>l</font><font style='font-family:Arial;font-size:10pt;color:#666666;vertical-align:top;text-align:left;'> Text 2 </font><font style='font-family:Wingdings;font-size:8.0pt;color:#009DD9;mso-font-charset:2;'>l</font><font style='font-family:Arial;font-size:10pt;color:#666666;vertical-align:top;text-align:left;'> Text 3 </font><font style='font-family:Wingdings;font-size:8.0pt;color:#009DD9;mso-font-charset:2;'>l</font><font style='font-family:Arial;font-size:10pt;color:#666666;vertical-align:top;text-align:left;'> Text 4 </font>");
//Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(EasyWayForChartSetup.class);
// Create new workbook
Workbook workbook = new Workbook(FileFormatType.XLSX);
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Add data for chart
// Category Axis Values
worksheet.getCells().get("A2").putValue("C1");
worksheet.getCells().get("A3").putValue("C2");
worksheet.getCells().get("A4").putValue("C3");
// First vertical series
worksheet.getCells().get("B1").putValue("T1");
worksheet.getCells().get("B2").putValue(6);
worksheet.getCells().get("B3").putValue(3);
worksheet.getCells().get("B4").putValue(2);
// Second vertical series
worksheet.getCells().get("C1").putValue("T2");
worksheet.getCells().get("C2").putValue(7);
worksheet.getCells().get("C3").putValue(2);
worksheet.getCells().get("C4").putValue(5);
// Third vertical series
worksheet.getCells().get("D1").putValue("T3");
worksheet.getCells().get("D2").putValue(8);
worksheet.getCells().get("D3").putValue(4);
worksheet.getCells().get("D4").putValue(2);
// Create Column chart with easy way
int idx = worksheet.getCharts().add(ChartType.COLUMN, 6, 5, 20, 13);
Chart ch = worksheet.getCharts().get(idx);
ch.setChartDataRange("A1:D4", true);
// Save the workbook
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(EditingHyperlinksOfWorksheet.class);
Workbook workbook = new Workbook(dataDir + "source.xlsx");
Worksheet worksheet = workbook.getWorksheets().get(0);
for (int i = 0; i < worksheet.getHyperlinks().getCount(); i++) {
Hyperlink hl = worksheet.getHyperlinks().get(i);
hl.setAddress("http://www.aspose.com");
}
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExceltoHTMLPresentationPreferenceOption.class);
// Instantiate the Workbook
// Load an Excel file
Workbook workbook = new Workbook(dataDir + "HiddenCol.xlsx");
// Create HtmlSaveOptions object
HtmlSaveOptions options = new HtmlSaveOptions();
// Set the Presenation preference option
options.setPresentationPreference(true);
// Save the Excel file to HTML with specified option
workbook.save(dataDir + "outPresentationlayout1.html");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExceltoPDF.class);
// Initialize a new Workbook
// Open an Excel file
Workbook workbook = new Workbook(dataDir + "Mybook.xls");
// Implement one page per worksheet option
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);
// Save the PDF file
workbook.save(dataDir + "OutputFile.pdf", pdfSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExportCharttoSVG.class);
// Create workbook object from source file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access first chart inside the worksheet
Chart chart = worksheet.getCharts().get(0);
// Set image or print options
// with SVGFitToViewPort true
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setSaveFormat(SaveFormat.SVG);
opts.setSVGFitToViewPort(true);
// Save the chart to svg format
chart.toImage(dataDir + "out.svg", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Load excel file containing custom properties
Workbook workbook = new Workbook("sourceWithCustProps.xlsx");
// Create an instance of PdfSaveOptions and pass SaveFormat to the constructor
PdfSaveOptions pdfSaveOpt = new PdfSaveOptions(SaveFormat.PDF);
// Set CustomPropertiesExport property to PdfCustomPropertiesExport.Standard
pdfSaveOpt.setCustomPropertiesExport(PdfCustomPropertiesExport.STANDARD);
// Save the workbook to PDF format while passing the object of PdfSaveOptions
workbook.save("outSourceWithCustProps.pdf", pdfSaveOpt);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExportExceltoHTML.class);
// Create your workbook
Workbook wb = new Workbook();
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Fill worksheet with some integer values
for (int r = 0; r < 10; r++) {
for (int c = 0; c < 10; c++) {
ws.getCells().get(r, c).putValue(r * 1);
}
}
// Save your workbook in HTML format and export gridlines
HtmlSaveOptions opts = new HtmlSaveOptions();
opts.setExportGridLines(true);
wb.save(dataDir + "output.html", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExportRangeofCells.class);
// Create workbook from source file.
Workbook workbook = new Workbook(dataDir + "aspose-sample.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Set the print area with your desired range
worksheet.getPageSetup().setPrintArea("E8:H15");
// Set all margins as 0
worksheet.getPageSetup().setLeftMargin(0);
worksheet.getPageSetup().setRightMargin(0);
worksheet.getPageSetup().setTopMargin(0);
worksheet.getPageSetup().setBottomMargin(0);
// Set OnePagePerSheet option as true
ImageOrPrintOptions options = new ImageOrPrintOptions();
options.setOnePagePerSheet(true);
options.setImageFormat(ImageFormat.getJpeg());
// Take the image of your worksheet
SheetRender sr = new SheetRender(worksheet, options);
sr.toImage(0, dataDir + "out.jpg");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class ExportStreamProvider implements IStreamProvider {
private String outputDir;
public ExportStreamProvider(String dir) {
outputDir = dir;
System.out.println(outputDir);
}
@Override
public void closeStream(StreamProviderOptions options) throws Exception {
if (options != null && options.getStream() != null) {
options.getStream().close();
}
}
@Override
public void initStream(StreamProviderOptions options) throws Exception {
System.out.println(options.getDefaultPath());
File file = new File(outputDir);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
String defaultPath = options.getDefaultPath();
String path = outputDir + defaultPath.substring(defaultPath.lastIndexOf("/") + 1);
options.setCustomPath(path);
options.setStream(new FileOutputStream(path));
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExportWorksheettoImage.class);
// Create workbook object from source file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
/*
* Set image or print options, We want one page per sheet, The image format is in png And desired dimensions are
* 400x400
*/
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setOnePagePerSheet(true);
opts.setImageFormat(ImageFormat.getPng());
opts.setDesiredSize(400, 400);
// Render sheet into image
SheetRender sr = new SheetRender(worksheet, opts);
sr.toImage(0, dataDir + "output.png");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ExportXmlDataOfXmlMap.class) + "articles/";
//Load source workbook
Workbook wb = new Workbook(dataDir + "sample_Export-Xml-Data-linked.xlsx");
//Export all XML data from all XML Maps inside the Workbook
for (int i = 0; i < wb.getWorksheets().getXmlMaps().getCount(); i++)
{
//Access the XML Map
XmlMap map = wb.getWorksheets().getXmlMaps().get(i);
//Exports its XML Data
wb.exportXml(map.getName(), dataDir + map.getName() + ".xml");
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExtractImagesfromWorksheets.class);
// Open a template Excel file
Workbook workbook = new Workbook(dataDir + "book1.xls");
// Get the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Get the first Picture in the first worksheet
Picture pic = worksheet.getPictures().get(0);
// Set the output image file path
String fileName = "aspose-logo.Jpg";
String picformat = pic.getImageFormat().toString();
// Note: you may evaluate the image format before specifying the image path
// Define ImageOrPrintOptions
ImageOrPrintOptions printoption = new ImageOrPrintOptions();
// Specify the image format
printoption.setImageFormat(ImageFormat.getJpeg());
// Save the image
pic.toImage(dataDir + fileName + picformat, printoption);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExtractOLEObjects.class);
// Instantiating a Workbook object, Open the template file.
Workbook workbook = new Workbook(dataDir + "oleFile.xlsx");
// Get the OleObject Collection in the first worksheet.
OleObjectCollection objects = workbook.getWorksheets().get(0).getOleObjects();
// Loop through all the OleObjects and extract each object in the worksheet.
for (int i = 0; i < objects.getCount(); i++) {
OleObject object = objects.get(i);
// Specify the output filename.
String fileName = "D:/object" + i + ".";
// Specify each file format based on the OleObject format type.
switch (object.getFileFormatType()) {
case FileFormatType.DOCX:
fileName += "docx";
break;
case FileFormatType.XLSX:
fileName += "xlsx";
break;
case FileFormatType.PPTX:
fileName += "pptx";
break;
case FileFormatType.PDF:
fileName += "pdf";
break;
case FileFormatType.UNKNOWN:
fileName += "jpg";
break;
default:
// ........
break;
}
// Save the OleObject as a new excel file if the object type is xls.
if (object.getFileFormatType() == FileFormatType.XLSX) {
byte[] bytes = object.getObjectData();
InputStream is = new ByteArrayInputStream(bytes);
Workbook oleBook = new Workbook(is);
oleBook.getSettings().setHidden(false);
oleBook.save(fileName);
}
// Create the files based on the OleObject format types.
else {
FileOutputStream fos = new FileOutputStream(fileName);
fos.write(object.getObjectData());
fos.close();
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ExtractThemeData.class);
// Create workbook object
Workbook workbook = new Workbook(dataDir + "TestBook.xlsx");
// Extract theme name applied to this workbook
System.out.println(workbook.getTheme());
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access cell A1
Cell cell = worksheet.getCells().get("A1");
// Get the style object
Style style = cell.getStyle();
// Extract theme color applied to this cell
System.out.println(style.getForegroundThemeColor().getColorType() == ThemeColorType.ACCENT_2);
// Extract theme color applied to the bottom border of the cell
Border bot = style.getBorders().getByBorderType(BorderType.BOTTOM_BORDER);
System.out.println(bot.getThemeColor().getColorType() == ThemeColorType.ACCENT_1);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class FilePathProvider {
// Gets the full path of the file by worksheet name when exporting worksheet to html separately.
// So the references among the worksheets could be exported correctly.
public String getFullName(String sheetName) {
String dataDir = Utils.getDataDir(FilePathProvider.class);
if ("Sheet2".equals(sheetName)) {
return dataDir + "Sheet2.html";
} else if ("Sheet3".equals(sheetName)) {
return dataDir + "Sheet3.html";
}
return "";
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(FilterDataWhileLoadingWorkbook.class);
// Set the load options, we only want to load shapes and do not want to
// load data
LoadOptions opts = new LoadOptions(LoadFormat.XLSX);
opts.setLoadDataFilterOptions(LoadDataFilterOptions.SHAPE);
// Create workbook object from sample excel file using load options
Workbook wb = new Workbook(dataDir + "sample.xlsx", opts);
// Save the output in pdf format
wb.save(dataDir + "output.pdf", SaveFormat.PDF);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(FilterObjectsLoadingWorkbook.class) + "articles/";
//Filter charts from entire workbook
LoadOptions ldOpts = new LoadOptions();
ldOpts.setLoadFilter(new LoadFilter(LoadDataFilterOptions.ALL & ~LoadDataFilterOptions.CHART));
//Load the workbook with above filter
Workbook wb = new Workbook(dataDir + "sampleFilterCharts.xlsx", ldOpts);
//Save entire worksheet into a single page
PdfSaveOptions opts = new PdfSaveOptions();
opts.setOnePagePerSheet(true);
//Save the workbook in pdf format with the above pdf save options
wb.save(dataDir + "sampleFilterCharts.pdf", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class FilterObjectsLoadingWorksheets {
// Implement your own custom load filter, it will enable you to filter your
// individual worksheet
class CustomLoadFilter extends LoadFilter {
public void startSheet(Worksheet sheet) {
if (sheet.getName().equals("NoCharts")) {
// Load everything and filter charts
this.setLoadDataFilterOptions(LoadDataFilterOptions.ALL& ~LoadDataFilterOptions.CHART);
}
if (sheet.getName().equals("NoShapes")) {
// Load everything and filter shapes
this.setLoadDataFilterOptions(LoadDataFilterOptions.ALL& ~LoadDataFilterOptions.SHAPE);
}
if (sheet.getName().equals("NoConditionalFormatting")) {
// Load everything and filter conditional formatting
this.setLoadDataFilterOptions(LoadDataFilterOptions.ALL& ~LoadDataFilterOptions.CONDITIONAL_FORMATTING);
}
}// End StartSheet method.
}// End CustomLoadFilter class.
public static void main(String[] args) throws Exception {
FilterObjectsLoadingWorksheets pg = new FilterObjectsLoadingWorksheets();
pg.Run();
}
public void Run() throws Exception {
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(FilterObjectsLoadingWorksheets.class) + "articles/";
// Filter worksheets using custom load filter
LoadOptions ldOpts = new LoadOptions();
ldOpts.setLoadFilter(new CustomLoadFilter());
// Load the workbook with above filter
Workbook wb = new Workbook(dataDir + "sampleFilterDifferentObjects.xlsx", ldOpts);
// Take the image of all worksheets one by one
for (int i = 0; i < wb.getWorksheets().getCount(); i++) {
// Access worksheet at index i
Worksheet ws = wb.getWorksheets().get(i);
// Create image or print options, we want the image of entire
// worksheet
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setOnePagePerSheet(true);
opts.setImageFormat(ImageFormat.getPng());
// Convert worksheet into image
SheetRender sr = new SheetRender(ws, opts);
sr.toImage(0, dataDir + ws.getName() + ".png");
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(FindAbsolutePositionOfShape.class);
// Load the sample Excel file inside the workbook object
Workbook workbook = new Workbook("sample.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the first shape inside the worksheet
Shape shape = worksheet.getShapes().get(0);
// Displays the absolute position of the shape
System.out.println("Absolute Position of this Shape is (" + shape.getLeftToCorner() + " , "
+ shape.getTopToCorner() + ")");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(FindCellsWithSpecificStyle.class);
Workbook workbook = new Workbook(dataDir + "TestBook.xlsx");
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the style of cell A1
Style style = worksheet.getCells().get("A1").getStyle();
// Specify the style for searching
FindOptions options = new FindOptions();
options.setStyle(style);
Cell nextCell = null;
do {
// Find the cell that has a style of cell A1
nextCell = worksheet.getCells().find(null, nextCell, options);
if (nextCell == null)
break;
// Change the text of the cell
nextCell.putValue("Found");
} while (true);
workbook.save(dataDir + "out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(FindDataPoints.class) + "articles/";
// Load source excel file containing Bar of Pie chart
Workbook wb = new Workbook(dataDir + "PieBars.xlsx");
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Access first chart which is Bar of Pie chart and calculate it
Chart ch = ws.getCharts().get(0);
ch.calculate();
// Access the chart series
Series srs = ch.getNSeries().get(0);
// Print the data points of the chart series and check
// its IsInSecondaryPlot property to determine if data point is inside
// the bar or pie
for (int i = 0; i < srs.getPoints().getCount(); i++) {
// Access chart point
ChartPoint cp = srs.getPoints().get(i);
// Skip null values
if (cp.getYValue() == null)
continue;
// Print the chart point value and see if it is inside bar or pie
// If the IsInSecondaryPlot is true, then the data point is inside
// bar
// otherwise it is inside the pie
System.out.println("Value: " + cp.getYValue());
System.out.println("IsInSecondaryPlot: " + cp.isInSecondaryPlot());
System.out.println();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public static void main(String[] args) throws Exception {
// The path to the documents directory
String dataDir = Utils.getDataDir(FindReferenceCellsFromExternalConnection.class);
// Load workbook object
Workbook workbook = new Workbook(dataDir + "sample.xlsm");
// Check all the connections inside the workbook
for (int i = 0; i < workbook.getDataConnections().getCount(); i++) {
ExternalConnection externalConnection = workbook.getDataConnections().get(i);
System.out.println("connection: " + externalConnection.getName());
PrintTables(workbook, externalConnection);
System.out.println();
}
}
public static void PrintTables(Workbook workbook, ExternalConnection ec) {
// Iterate all the worksheets
for (int j = 0; j < workbook.getWorksheets().getCount(); j++) {
Worksheet worksheet = workbook.getWorksheets().get(j);
// Check all the query tables in a worksheet
for (int k = 0; k < worksheet.getQueryTables().getCount(); k++) {
QueryTable qt = worksheet.getQueryTables().get(k);
// Check if query table is related to this external connection
if (ec.getId() == qt.getConnectionId() && qt.getConnectionId() >= 0) {
// Print the query table name and print its "Refers To"
// range
System.out.println("querytable " + qt.getName());
String n = qt.getName().replace('+', '_').replace('=', '_');
Name name = workbook.getWorksheets().getNames().get("'" + worksheet.getName() + "'!" + n);
if (name != null) {
Range range = name.getRange();
if (range != null) {
System.out.println("Refers To: " + range.getRefersTo());
}
}
}
}
// Iterate all the list objects in this worksheet
for (int k = 0; k < worksheet.getListObjects().getCount(); k++) {
ListObject table = worksheet.getListObjects().get(k);
// Check the data source type if it is query table
if (table.getDataSourceType() == TableDataSourceType.QUERY_TABLE) {
// Access the query table related to list object
QueryTable qt = table.getQueryTable();
// Check if query table is related to this external
// connection
if (ec.getId() == qt.getConnectionId() && qt.getConnectionId() >= 0) {
// Print the query table name and print its refersto
// range
System.out.println("querytable " + qt.getName());
System.out.println("Table " + table.getDisplayName());
System.out.println("refersto: " + worksheet.getName() + "!"
+ CellsHelper.cellIndexToName(table.getStartRow(), table.getStartColumn()) + ":"
+ CellsHelper.cellIndexToName(table.getEndRow(), table.getEndColumn()));
}
}
}
}
}// end-PrintTables
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(FitAllWorksheetColumns.class);
// Create and initialize an instance of Workbook
Workbook book = new Workbook(dataDir + "TestBook.xlsx");
// Create and initialize an instance of PdfSaveOptions
PdfSaveOptions saveOptions = new PdfSaveOptions(SaveFormat.PDF);
// Set AllColumnsInOnePagePerSheet to true
saveOptions.setAllColumnsInOnePagePerSheet(true);
// Save Workbook to PDF fromart by passing the object of PdfSaveOptions
book.save(dataDir + "output.pdf", saveOptions);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(FormatPivotTableCells.class);
// Create workbook object from source file containing pivot table
Workbook workbook = new Workbook(dataDir + "pivotTable_test.xlsx");
// Access the worksheet by its name
Worksheet worksheet = workbook.getWorksheets().get("PivotTable");
// Access the pivot table
PivotTable pivotTable = worksheet.getPivotTables().get(0);
// Create a style object with background color light blue
Style style = workbook.createStyle();
style.setPattern(BackgroundType.SOLID);
style.setBackgroundColor(Color.getLightBlue());
// Format entire pivot table with light blue color
pivotTable.formatAll(style);
// Create another style object with yellow color
style = workbook.createStyle();
style.setPattern(BackgroundType.SOLID);
style.setBackgroundColor(Color.getYellow());
// Format the cells of the first row of the pivot table with yellow color
for (int col = 0; col < 5; col++) {
pivotTable.format(1, col, style);
}
// Save the workbook object
workbook.save(dataDir + "out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GenerateChartByProcessingSmartMarkers.class);
// Create an instance of Workbook
Workbook book = new Workbook();
// Access the first (default) Worksheet from the collection
Worksheet dataSheet = book.getWorksheets().get(0);
// Name the first Worksheet for referencing
dataSheet.setName("ChartData");
// Access the CellsCollection of ChartData Worksheet
Cells cells = dataSheet.getCells();
// Place the markers in the Worksheet according to desired layout
cells.get("A1").putValue("&=$Headers(horizontal)");
cells.get("A2").putValue("&=$Year2000(horizontal)");
cells.get("A3").putValue("&=$Year2005(horizontal)");
cells.get("A4").putValue("&=$Year2010(horizontal)");
cells.get("A5").putValue("&=$Year2015(horizontal)");
// Create string arrays which will serve as data sources to the smart markers
String[] headers = new String[] { "", "Item 1", "Item 2", "Item 3", "Item 4", "Item 5", "Item 6", "Item 7",
"Item 8", "Item 9", "Item 10", "Item 11", "Item 12" };
String[] year2000 = new String[] { "2000", "310", "0", "110", "15", "20", "25", "30", "1222", "200", "421",
"210", "133" };
String[] year2005 = new String[] { "2005", "508", "0", "170", "280", "190", "400", "105", "132", "303", "199",
"120", "100" };
String[] year2010 = new String[] { "2010", "0", "210", "230", "1420", "1530", "160", "170", "110", "199", "129",
"120", "230" };
String[] year2015 = new String[] { "2015", "2818", "320", "340", "260", "210", "310", "220", "0", "0", "0", "0",
"122" };
// Create an instance of WorkbookDesigner
WorkbookDesigner designer = new WorkbookDesigner();
// Set the Workbook property for the instance of WorkbookDesigner
designer.setWorkbook(book);
// Set data sources for smart markers
designer.setDataSource("Headers", headers);
designer.setDataSource("Year2000", year2000);
designer.setDataSource("Year2005", year2005);
designer.setDataSource("Year2010", year2010);
designer.setDataSource("Year2015", year2015);
// Process the designer spreadsheet against the provided data sources
designer.process();
// Convert all string values of ChartData to numbers
// This is an additional step as we have imported the string values
dataSheet.getCells().convertStringToNumericValue();
// Save the number of rows & columns from the ChartData in separate variables
// These values will be used later to identify the chart's data range from ChartData
int chartRows = dataSheet.getCells().getMaxDataRow() + 1;
int chartCols = dataSheet.getCells().getMaxDataColumn() + 1;
// Add a new Worksheet of type Chart to Workbook
int chartSheetIdx = book.getWorksheets().add(SheetType.CHART);
// Access the newly added Worksheet via its index
Worksheet chartSheet = book.getWorksheets().get(chartSheetIdx);
// Name the Worksheet
chartSheet.setName("Chart");
// Add a chart of type ColumnStacked to newly added Worksheet
int chartIdx = chartSheet.getCharts().add(ChartType.COLUMN_STACKED, 0, 0, chartRows, chartCols);
// Access the newly added Chart via its index
Chart chart = chartSheet.getCharts().get(chartIdx);
// Identify the chart's data range
Range dataRange = dataSheet.getCells().createRange(0, 1, chartRows, chartCols - 1);
// Set the data range for the chart
chart.setChartDataRange(dataRange.getRefersTo(), false);
// Set the chart to size with window
chart.setSizeWithWindow(true);
// Set the format for the tick labels
chart.getValueAxis().getTickLabels().setNumberFormat("$###,### K");
// Set chart title
chart.getTitle().setText("Sales Summary");
// Set ChartSheet an active sheet
book.getWorksheets().setActiveSheetIndex(chartSheetIdx);
// Save the final result
book.save(dataDir + "report.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SpecifyJoborDocumentName.class);
// Create workbook object from source excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the cell which contains conditional formatting databar
Cell cell = worksheet.getCells().get("C1");
// Get the conditional formatting of the cell
FormatConditionCollection fcc = cell.getFormatConditions();
// Access the conditional formatting databar
DataBar dbar = fcc.get(0).getDataBar();
// Create image or print options
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setImageFormat(ImageFormat.getPng());
// Get the image bytes of the databar
byte[] imgBytes = dbar.toImage(cell, opts);
// Write image bytes on the disk
FileOutputStream out = new FileOutputStream(dataDir + "databar.png");
out.write(imgBytes);
out.close();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GenerateThumbnailofWorksheet.class);
// Instantiate and open an Excel file
Workbook book = new Workbook(dataDir + "book1.xls");
// Define ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
// Set the vertical and horizontal resolution
imgOptions.setVerticalResolution(200);
imgOptions.setHorizontalResolution(200);
// Set the image's format
imgOptions.setImageFormat(ImageFormat.getJpeg());
// One page per sheet is enabled
imgOptions.setOnePagePerSheet(true);
// Get the first worksheet
Worksheet sheet = book.getWorksheets().get(0);
// Render the sheet with respect to specified image/print options
SheetRender sr = new SheetRender(sheet, imgOptions);
// Render the image for the sheet
sr.toImage(0, "mythumb.jpg");
// Creating Thumbnail
java.awt.Image img = ImageIO.read(new File(dataDir + "mythumb.jpg")).getScaledInstance(100, 100, BufferedImage.SCALE_SMOOTH);
BufferedImage img1 = new BufferedImage(100, 100, BufferedImage.TYPE_INT_RGB);
img1.createGraphics().drawImage(
ImageIO.read(new File(dataDir + "mythumb.jpg")).getScaledInstance(100, 100, Image.SCALE_SMOOTH), 0, 0, null);
ImageIO.write(img1, "jpg", new File(dataDir + "thumbnail_out.jpg"));
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetCellObject.class);
// Create workbook object from source excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access first pivot table inside the worksheet
PivotTable pivotTable = worksheet.getPivotTables().get(0);
// Access cell by display name of 2nd data field of the pivot table
String displayName = pivotTable.getDataFields().get(1).getDisplayName();
Cell cell = pivotTable.getCellByDisplayName(displayName);
// Access cell style and set its fill color and font color
Style style = cell.getStyle();
style.setForegroundColor(Color.getLightBlue());
style.getFont().setColor(Color.getBlack());
// Set the style of the cell
pivotTable.format(cell.getRow(), cell.getColumn(), style);
// Save workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetCellStringValue.class);
// Create workbook
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access cell A1
Cell cell = worksheet.getCells().get("A1");
// Put value inside the cell
cell.putValue(0.012345);
// Format the cell that it should display 0.01 instead of 0.012345
Style style = cell.getStyle();
style.setNumber(2);
cell.setStyle(style);
// Get string value as Cell Style
String value = cell.getStringValue(CellValueFormatStrategy.CELL_STYLE);
System.out.println(value);
// Get string value without any formatting
value = cell.getStringValue(CellValueFormatStrategy.NONE);
System.out.println(value);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(GetDataConnection.class);
String inputPath = dataDir + "WebQuerySample.xlsx";
Workbook workbook = new Workbook(inputPath);
ExternalConnection connection = workbook.getDataConnections().get(0);
if (connection instanceof WebQueryConnection) {
WebQueryConnection webQuery = (WebQueryConnection) connection;
System.out.println("Web Query URL: " + webQuery.getUrl());
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetWorksheetOfChart.class);
// Create workbook object from source Excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the first chart inside the worksheet
Chart chart = worksheet.getCharts().get(0);
// Calculate the Chart first to get the Equation Text of Trendline
chart.calculate();
// Access the Trendline
Trendline trendLine = chart.getNSeries().get(0).getTrendLines().get(0);
// Read the Equation Text of Trendline
System.out.println("Equation Text: " + trendLine.getDataLabels().getText());
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(GetFontsUsedinWorkbook.class) + "articles/";
//Load source workbook
Workbook wb = new Workbook(dataDir + "sampleGetFonts.xlsx");
//Get all the fonts inside the workbook
com.aspose.cells.Font[] fnts = wb.getFonts();
//Print all the fonts
for(int i=0; i<fnts.length; i++)
{
System.out.println(fnts[i]);
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetNotificationsWhileMergingData.class);
// Instantiate a new Workbook designer
WorkbookDesigner report = new WorkbookDesigner();
// Get the first worksheet of the workbook
Worksheet sheet = report.getWorkbook().getWorksheets().get(0);
/*
* Set the Variable Array marker to a cell. You may also place this Smart Marker into a template file manually using Excel
* and then open this file via WorkbookDesigner
*/
sheet.getCells().get("A1").putValue("&=$VariableArray");
// Set the data source for the marker(s)
report.setDataSource("VariableArray", new String[] { "English", "Arabic", "Hindi", "Urdu", "French" });
// Set the CallBack property
report.setCallBack(new SmartMarkerCallBack(report.getWorkbook()));
// Process the markers
report.process(false);
// Save the result
report.getWorkbook().save(dataDir);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(GetSettheClassIdentifier.class) + "articles/";
//Load your sample workbook which contains embedded PowerPoint ole object
Workbook wb = new Workbook(dataDir + "sample.xls");
//Access its first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Access first ole object inside the worksheet
OleObject oleObj = ws.getOleObjects().get(0);
//Get the class identifier of ole object in bytes and convert them into GUID
byte[] classId = oleObj.getClassIdentifier();
//Position of the bytes and formatting
int[] pos = {3, 2, 1, 0, -1, 5, 4, -1, 7, 6, -1, 8, 9, -1, 10, 11, 12, 13, 14,15};
StringBuilder sb = new StringBuilder();
for(int i=0; i<pos.length; i++)
{
if(pos[i]==-1)
{
sb.append("-");
}
else
{
sb.append(String.format("%02X", classId[pos[i]]&0xff));
}
}
//Get the GUID from conversion
String guid = sb.toString();
//Print the GUID
System.out.println(guid);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetSetThemeColors.class);
// Instantiate Workbook object
// Open an exiting excel file
Workbook workbook = new Workbook(dataDir + "book1.xlsx");
// Get the Background1 theme color
Color c = workbook.getThemeColor(ThemeColorType.BACKGROUND_1);
// Print the color
System.out.println("theme color Background1: " + c);
// Get the Accent2 theme color
c = workbook.getThemeColor(ThemeColorType.ACCENT_1);
// Print the color
System.out.println("theme color Accent2: " + c);
// Change the Background1 theme color
workbook.setThemeColor(ThemeColorType.BACKGROUND_1, Color.getRed());
// Get the updated Background1 theme color
c = workbook.getThemeColor(ThemeColorType.BACKGROUND_1);
// Print the updated color for confirmation
System.out.println("theme color Background1 changed to: " + c);
// Change the Accent2 theme color
workbook.setThemeColor(ThemeColorType.ACCENT_1, Color.getBlue());
// Get the updated Accent2 theme color
c = workbook.getThemeColor(ThemeColorType.ACCENT_1);
// Print the updated color for confirmation
System.out.println("theme color Accent2 changed to: " + c);
// Save the updated file
workbook.save(dataDir + "GetAndSetThemeColorBook.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public static void main(String[] args)
throws Exception {
String dataDir = Utils.getDataDir(GetSmartMarkerNotifications.class);
String outputPath = dataDir + "Output.xlsx";
//Instantiate a new Workbook designer
WorkbookDesigner report = new WorkbookDesigner();
//Get the first worksheet of the workbook
Worksheet sheet = report.getWorkbook().getWorksheets().get(0);
//Set the Variable Array marker to a cell
//You may also place this Smart Marker into a template file manually using Excel and then open this file via WorkbookDesigner
sheet.getCells().get("A1").putValue("&=$VariableArray");
//Set the data source for the marker(s)
report.setDataSource("VariableArray", new String[]{"English", "Arabic", "Hindi", "Urdu", "French"});
//Set the CallBack property
report.setCallBack(new SmartMarkerCallBack(report.getWorkbook()));
//Process the markers
report.process(false);
//Save the result
report.getWorkbook().save(outputPath);
System.out.println("File saved " + outputPath);
}
}
class SmartMarkerCallBack implements ISmartMarkerCallBack {
Workbook workbook;
SmartMarkerCallBack(Workbook workbook) {
this.workbook = workbook;
}
@Override
public void process(int sheetIndex, int rowIndex, int colIndex, String tableName, String columnName) {
System.out.println("Processing Cell: " + workbook.getWorksheets().get(sheetIndex).getName() + "!" + CellsHelper.cellIndexToName(rowIndex, colIndex));
System.out.println("Processing Marker: " + tableName + "." + columnName);
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetValidationAppliedonCell.class);
// Instantiate the workbook from sample Excel file
Workbook workbook = new Workbook(dataDir + "book1.xlsx");
// Access its first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Cell C1 has the Decimal Validation applied on it.
// It can take only the values Between 10 and 20
Cell cell = worksheet.getCells().get("C1");
// Access the valditation applied on this cell
Validation validation = cell.getValidation();
// Read various properties of the validation
System.out.println("Reading Properties of Validation");
System.out.println("--------------------------------");
System.out.println("Type: " + validation.getType());
System.out.println("Operator: " + validation.getOperator());
System.out.println("Formula1: " + validation.getFormula1());
System.out.println("Formula2: " + validation.getFormula2());
System.out.println("Ignore blank: " + validation.getIgnoreBlank());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetVersionNumberofApplication.class);
// Create a workbook reference
Workbook workbook = null;
// Print the version number of Excel 2003 XLS file
workbook = new Workbook(dataDir + "Excel2003.xls");
System.out.println("Excel 2003 XLS Version: " + workbook.getBuiltInDocumentProperties().getVersion());
// Print the version number of Excel 2007 XLS file
workbook = new Workbook(dataDir + "Excel2007.xls");
System.out.println("Excel 2007 XLS Version: " + workbook.getBuiltInDocumentProperties().getVersion());
// Print the version number of Excel 2010 XLS file
workbook = new Workbook(dataDir + "Excel2010.xls");
System.out.println("Excel 2010 XLS Version: " + workbook.getBuiltInDocumentProperties().getVersion());
// Print the version number of Excel 2013 XLS file
workbook = new Workbook(dataDir + "Excel2013.xls");
System.out.println("Excel 2013 XLS Version: " + workbook.getBuiltInDocumentProperties().getVersion());
// Print the version number of Excel 2007 XLSX file
workbook = new Workbook(dataDir + "Excel2007.xlsx");
System.out.println("Excel 2007 XLSX Version: " + workbook.getBuiltInDocumentProperties().getVersion());
// Print the version number of Excel 2010 XLSX file
workbook = new Workbook(dataDir + "Excel2010.xlsx");
System.out.println("Excel 2010 XLSX Version: " + workbook.getBuiltInDocumentProperties().getVersion());
// Print the version number of Excel 2013 XLSX file
workbook = new Workbook(dataDir + "Excel2013.xlsx");
System.out.println("Excel 2013 XLSX Version: " + workbook.getBuiltInDocumentProperties().getVersion());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(GetWorksheetOfChart.class);
// Create workbook from sample Excel file
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
// Access first worksheet of the workbook
Worksheet worksheet = workbook.getWorksheets().get(0);
// Print worksheet name
System.out.println("Sheet Name: " + worksheet.getName());
// Access the first chart inside this worksheet
Chart chart = worksheet.getCharts().get(0);
// Access the chart's sheet and display its name again
System.out.println("Chart's Sheet Name: " + chart.getWorksheet().getName());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//This function will return the sub total name
public String getTotalName(int functionType)
{
return "Chinese Total - 可能的用法";
}
//This function will return the grand total name
public String getGrandTotalName(int functionType)
{
return "Chinese Grand Total - 可能的用法";
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(HidingDisplayOfZeroValues.class);
// Create a new Workbook object
Workbook workbook = new Workbook(dataDir + "book1.xlsx");
// Get First worksheet of the workbook
Worksheet sheet = workbook.getWorksheets().get(0);
// Hide the zero values in the sheet
sheet.setDisplayZeros(false);
// Save the workbook
workbook.save(dataDir + "output.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(HtmlExportFrameScripts.class);
// Open the required workbook to convert
Workbook w = new Workbook(dataDir + "Sample1.xlsx");
// Disable exporting frame scripts and document properties
HtmlSaveOptions options = new HtmlSaveOptions();
options.setExportFrameScriptsAndProperties(false);
// Save workbook as HTML
w.save(dataDir + "output.html", options);
System.out.println("File saved");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(HtmlSaveOptions.class);
Workbook wb = new Workbook(dataDir + "sample.xlsx");
HtmlSaveOptions options = new HtmlSaveOptions();
options.setStreamProvider(new ExportStreamProvider(dataDir));
wb.save(dataDir + "out.html", options);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(Implement1904DateSystem.class);
// Initialize a new Workbook
Workbook workbook = new Workbook(dataDir + "Mybook.xlsx");
// Implement 1904 date system
workbook.getSettings().setDate1904(true);
// Save the excel file
workbook.save(dataDir + "OutPut.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class CustomEngine extends AbstractCalculationEngine {
public void calculate(CalculationData data) {
if (data.getFunctionName().toUpperCase().equals("SUM") == true) {
double val = (double) data.getCalculatedValue();
val = val + 30;
data.setCalculatedValue(val);
}
}
}
public static void main(String[] args) throws Exception {
// The path to the documents directory.
String dataDir = Utils.getDataDir(ImplementCustomCalculationEngine.class);
Workbook workbook = new Workbook();
Worksheet sheet = workbook.getWorksheets().get(0);
Cell a1 = sheet.getCells().get("A1");
a1.setFormula("=Sum(B1:B2)");
sheet.getCells().get("B1").putValue(10);
sheet.getCells().get("B2").putValue(10);
// Without Custom Engine, the value of cell A1 will be 20
workbook.calculateFormula();
System.out.println("Without Custom Engine Value of A1: " + a1.getStringValue());
// With Custom Engine, the value of cell A1 will be 50
CalculationOptions opts = new CalculationOptions();
opts.setCustomEngine(new CustomEngine());
workbook.calculateFormula(opts);
System.out.println("With Custom Engine Value of A1: " + a1.getStringValue());
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public abstract class CalculateCustomFunctionWithoutWritingToWorksheet extends AbstractCalculationEngine {
public void Run() {
// TODO Auto-generated method stub
// Create a workbook
Workbook wb = new Workbook();
// Accesss first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Add some text in cell A1
ws.getCells().get("A1").putValue("Welcome to ");
// Create a calculation options with custom engine
CalculationOptions opts = new CalculationOptions();
opts.setCustomEngine(new CustomEngine());
// This line shows how you can call your own custom function without
// a need to write it in any worksheet cell
// After the execution of this line, it will return
// Welcome to Aspose.Cells.
Object ret = ws.calculateFormula("=A1 & MyCompany.CustomFunction()", opts);
// Print the calculated value on Console
System.out.println("Calculated Value: " + ret.toString());
}
}
public static void main(String[] args) throws Exception {
CalculateCustomFunctionWithoutWritingToWorksheet pg = new CalculateCustomFunctionWithoutWritingToWorksheet();
pg.Run();
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ImplementingNonSequentialRanges.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook();
// Adding a Name for non sequenced range
int index = workbook.getWorksheets().getNames().add("NonSequencedRange");
Name name = workbook.getWorksheets().getNames().get(index);
// Creating a non sequence range of cells
name.setRefersTo("=Sheet1!$A$1:$B$3,Sheet1!$E$5:$D$6");
// Save the workbook
workbook.save(dataDir + "dest.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ImplementSubtotalGrandTotallabels.class) + "articles/";
// Load your source workbook
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Set the glorbalization setting to change subtotal and grand total
// names
GlobalizationSettings gsi = new GlobalizationSettingsImp();
wb.getSettings().setGlobalizationSettings(gsi);
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Apply subtotal on A1:B10
CellArea ca = CellArea.createCellArea("A1", "B10");
ws.getCells().subtotal(ca, 0, ConsolidationFunction.SUM, new int[] { 2, 3, 4 });
// Set the width of the first column
ws.getCells().setColumnWidth(0, 40);
// Save the output excel file
wb.save(dataDir + "ImplementTotallabels_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ImportXMLMap.class);
// Create a workbook
Workbook workbook = new Workbook();
// URL that contains your XML data for mapping
String XML = "http://www.aspose.com/docs/download/attachments/434475650/sampleXML.txt";
// Import your XML Map data starting from cell A1
workbook.importXml(XML, "Sheet1", 0, 0);
// Save workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(InsertDeleteRows.class);
// Instantiate a Workbook object.
Workbook workbook = new Workbook(dataDir + "MyBook.xls");
// Get the first worksheet in the book.
Worksheet sheet = workbook.getWorksheets().get(0);
// Insert 10 rows at row index 2 (insertion starts at 3rd row)
sheet.getCells().insertRows(2, 10);
// Delete 5 rows now. (8th row - 12th row)
sheet.getCells().deleteRows(7, 5, true);
// Save the Excel file.
workbook.save(dataDir + "out_MyBook.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(InsertLinkedPicturefromWebAddress.class);
// Instantiate a new Workbook.
Workbook workbook = new Workbook();
// Insert a linked picture (from Web Address) to B2 Cell.
Picture pic = (Picture) workbook.getWorksheets().get(0).getShapes().addLinkedPicture(1, 1, 100, 100,
"http://www.aspose.com/Images/aspose-logo.jpg");
// Set the source of the inserted image.
pic.setSourceFullName("http://www.aspose.com/images/aspose-logo.gif");
// Set the height and width of the inserted image.
pic.setHeightInch(1.04);
pic.setWidthInch(2.6);
// Save the Excel file.
workbook.save(dataDir + "LinkedPicture.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(InsertPictureCellReference.class);
// Instantiate a new Workbook
Workbook workbook = new Workbook();
// Get the first worksheet's cells collection
Cells cells = workbook.getWorksheets().get(0).getCells();
// Add string values to the cells
cells.get("A1").putValue("A1");
cells.get("C10").putValue("C10");
// Add a blank picture to the D1 cell
Picture pic = (Picture) workbook.getWorksheets().get(0).getShapes().addPicture(0, 3, null, 10, 10);
// Set the size of the picture.
pic.setHeightCM(4.48);
pic.setWidthCM(5.28);
// Specify the formula that refers to the source range of cells
pic.setFormula("A1:C10");
// Update the shapes selected value in the worksheet
workbook.getWorksheets().get(0).getShapes().updateSelectedValue();
// Save the Excel file.
workbook.save(dataDir + "referencedpicture.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(InsertWebImageFromURL.class);
// Download image and store it in an object of InputStream
URL url = new URL("https://www.google.com/images/nav_logo100633543.png");
InputStream inStream = new BufferedInputStream(url.openStream());
// Create a new workbook
Workbook book = new Workbook();
// Get the first worksheet in the book
Worksheet sheet = book.getWorksheets().get(0);
// Get the first worksheet pictures collection
PictureCollection pictures = sheet.getPictures();
// Insert the picture from the stream to B2 cell
pictures.add(1, 1, inStream);
// Save the excel file
book.save(dataDir + "InsertedImage.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(KeepPrecisionOfLargeNumbers.class);
// Sample Html containing large number with digits greater than 15
String html = "<html>" + "<body>" + "<p>1234567890123456</p>" + "</body>" + "</html>";
// Convert Html to byte array
byte[] byteArray = html.getBytes();
// Set Html load options and keep precision true
HTMLLoadOptions loadOptions = new HTMLLoadOptions(LoadFormat.HTML);
loadOptions.setKeepPrecision(true);
// Convert byte array into stream
java.io.ByteArrayInputStream stream = new java.io.ByteArrayInputStream(byteArray);
// Create workbook from stream with Html load options
Workbook workbook = new Workbook(stream, loadOptions);
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Auto fit the sheet columns
worksheet.autoFitColumns();
// Save the workbook
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
System.out.println("File saved");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class LightCellsDataHandlerVisitCells implements LightCellsDataHandler {
public int cellCount;
public int formulaCount;
public int stringCount;
public LightCellsDataHandlerVisitCells() {
this.cellCount = 0;
this.formulaCount = 0;
this.stringCount = 0;
}
public int cellCount() {
return cellCount;
}
public int formulaCount() {
return formulaCount;
}
public int stringCount() {
return stringCount;
}
public boolean startSheet(Worksheet sheet) {
System.out.println("Processing sheet[" + sheet.getName() + "]");
return true;
}
public boolean startRow(int rowIndex) {
return true;
}
public boolean processRow(Row row) {
return true;
}
public boolean startCell(int column) {
return true;
}
public boolean processCell(Cell cell) {
this.cellCount = this.cellCount + 1;
if (cell.isFormula()) {
this.formulaCount = this.formulaCount + 1;
} else if (cell.getType() == CellValueType.IS_STRING) {
this.stringCount = this.stringCount + 1;
}
return false;
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
private final int sheetCount;
private final int maxRowIndex;
private final int maxColIndex;
private int rowIndex;
private int colIndex;
private final Style style1;
private final Style style2;
public LightCellsDataProviderDemo(Workbook wb, int sheetCount, int rowCount, int colCount) {
// set the variables/objects
this.sheetCount = sheetCount;
this.maxRowIndex = rowCount - 1;
this.maxColIndex = colCount - 1;
// add new style object with specific formattings
style1 = wb.createStyle();
Font font = style1.getFont();
font.setName("MS Sans Serif");
font.setSize(10);
font.setBold(true);
font.setItalic(true);
font.setUnderline(FontUnderlineType.SINGLE);
font.setColor(Color.fromArgb(0xffff0000));
style1.setHorizontalAlignment(TextAlignmentType.CENTER);
// create another style
style2 = wb.createStyle();
style2.setCustom("#,##0.00");
font = style2.getFont();
font.setName("Copperplate Gothic Bold");
font.setSize(8);
style2.setPattern(BackgroundType.SOLID);
style2.setForegroundColor(Color.fromArgb(0xff0000ff));
style2.setBorder(BorderType.TOP_BORDER, CellBorderType.THICK, Color.getBlack());
style2.setVerticalAlignment(TextAlignmentType.CENTER);
}
public boolean isGatherString() {
return false;
}
public int nextCell() {
if (colIndex < maxColIndex) {
colIndex++;
return colIndex;
}
return -1;
}
public int nextRow() {
if (rowIndex < maxRowIndex) {
rowIndex++;
colIndex = -1; // reset column index
if (rowIndex % 1000 == 0) {
System.out.println("Row " + rowIndex);
}
return rowIndex;
}
return -1;
}
public void startCell(Cell cell) {
if (rowIndex % 50 == 0 && (colIndex == 0 || colIndex == 3)) {
// do not change the content of hyperlink.
return;
}
if (colIndex < 10) {
cell.putValue("test_" + rowIndex + "_" + colIndex);
cell.setStyle(style1);
} else {
if (colIndex == 19) {
cell.setFormula("=Rand() + test!L1");
} else {
cell.putValue(rowIndex * colIndex);
}
cell.setStyle(style2);
}
}
public void startRow(Row row) {
row.setHeight(25);
}
public boolean startSheet(int sheetIndex) {
if (sheetIndex < sheetCount) {
// reset row/column index
rowIndex = -1;
colIndex = -1;
return true;
}
return false;
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class LightCellsTest1 {
public static void main(String[] args) throws Exception {
String dataDir = Utils.getDataDir(LightCellsTest1.class);
LoadOptions opts = new LoadOptions();
LightCellsDataHandlerVisitCells v = new LightCellsDataHandlerVisitCells();
opts.setLightCellsDataHandler((LightCellsDataHandler) v);
Workbook wb = new Workbook(dataDir + "LargeBook1.xlsx", opts);
int sheetCount = wb.getWorksheets().getCount();
System.out.println("Total sheets: " + sheetCount + ", cells: " + v.cellCount + ", strings: " + v.stringCount
+ ", formulas: " + v.formulaCount);
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(LimitNumberofPagesGenerated.class);
// Open an Excel file
Workbook wb = new Workbook(dataDir + "TestBook.xlsx");
// Instantiate the PdfSaveOption
PdfSaveOptions options = new PdfSaveOptions();
// Print only Page 3 and Page 4 in the output PDF
// Starting page index (0-based index)
options.setPageIndex(2);
// Number of pages to be printed
options.setPageCount(2);
// Save the PDF file
wb.save(dataDir + "outPDF1.pdf", options);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(LinkCellstoXmlMapElements.class) + "articles/";
// Load sample workbook
Workbook wb = new Workbook(dataDir + "LinkCellstoXmlMapElements_in.xlsx");
// Access the Xml Map inside it
XmlMap map = wb.getWorksheets().getXmlMaps().get(0);
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Map FIELD1 and FIELD2 to cell A1 and B2
ws.getCells().linkToXmlMap(map.getName(), 0, 0, "/root/row/FIELD1");
ws.getCells().linkToXmlMap(map.getName(), 1, 1, "/root/row/FIELD2");
// Map FIELD4 and FIELD5 to cell C3 and D4
ws.getCells().linkToXmlMap(map.getName(), 2, 2, "/root/row/FIELD4");
ws.getCells().linkToXmlMap(map.getName(), 3, 3, "/root/row/FIELD5");
// Map FIELD7 and FIELD8 to cell E5 and F6
ws.getCells().linkToXmlMap(map.getName(), 4, 4, "/root/row/FIELD7");
ws.getCells().linkToXmlMap(map.getName(), 5, 5, "/root/row/FIELD8");
// Save the workbook in xlsx format
wb.save(dataDir + "LinkCellstoXmlMapElements_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(LoadOrImportCSVFile.class);
String csvFile = dataDir + "sample.csv";
TxtLoadOptions opts = new TxtLoadOptions();
opts.setSeparator(',');
opts.setHasFormula(true);
// Load your CSV file with formulas in a Workbook object
Workbook workbook = new Workbook(csvFile, opts);
// You can also import your CSV file like this. The code below is importing CSV file starting from cell D4
Worksheet worksheet = workbook.getWorksheets().get(0);
worksheet.getCells().importCSV(csvFile, opts, 3, 3);
// Save your workbook in Xlsx format
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(Loadsourceexcelfile.class);
// Specify the load options and filter the data
// we do not want to load charts
LoadOptions options = new LoadOptions();
options.setLoadDataFilterOptions(LoadDataFilterOptions.ALL & ~LoadDataFilterOptions.CHART);
// Load the workbook with specified load options
Workbook workbook = new Workbook(dataDir + "sample.xlsx", options);
// Save the workbook in output format
workbook.save(dataDir + "output.pdf", SaveFormat.PDF);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(LoadSpecificWorksheetsinWorkbook.class);
//Define a new Workbook
Workbook workbook;
/// Load the workbook with the specified worksheet only.
LoadOptions loadOptions = new LoadOptions(LoadFormat.XLSX);
loadOptions.setLoadFilter(new CustomLoad());
// Creat the workbook.
workbook = new Workbook(dataDir+ "TestData.xlsx", loadOptions);
// Perform your desired task.
// Save the workbook.
workbook.save(dataDir+ "outputFile.out.xlsx");
public class CustomLoad extends LoadFilter
{
public void startSheet(Worksheet sheet)
{
if (sheet.getName() == "Sheet2")
{
// Load everything from worksheet "Sheet2"
this.setLoadDataFilterOptions(LoadDataFilterOptions.ALL);
}
else
{
// Load nothing
this.setLoadDataFilterOptions(LoadDataFilterOptions.NONE);
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(LoadWorkbook.class);
// Create a sample workbook and add some data inside the first worksheet
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.getWorksheets().get(0);
worksheet.getCells().get("P30").putValue("This is sample data.");
// Save the workbook in memory stream
ByteArrayOutputStream baout = new ByteArrayOutputStream();
workbook.save(baout, SaveFormat.XLSX);
// Get bytes and create byte array input stream
byte[] bts = baout.toByteArray();
ByteArrayInputStream bain = new ByteArrayInputStream(bts);
// Now load the workbook from memory stream with A5 paper size
LoadOptions opts = new LoadOptions(LoadFormat.XLSX);
opts.setPaperSize(PaperSizeType.PAPER_A_5);
workbook = new Workbook(bain, opts);
// Save the workbook in pdf format
workbook.save(dataDir + "output-a5.pdf");
// Now load the workbook again from memory stream with A3 paper size
opts = new LoadOptions(LoadFormat.XLSX);
opts.setPaperSize(PaperSizeType.PAPER_A_3);
workbook = new Workbook(bain, opts);
// Save the workbook in pdf format
workbook.save(dataDir + "output-a3.pdf");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(LockWordArtWatermark.class);
// Instantiate a new Workbook
Workbook workbook = new Workbook();
// Get the first default sheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Add Watermark
Shape wordart = sheet.getShapes().addTextEffect(MsoPresetTextEffect.TEXT_EFFECT_1, "CONFIDENTIAL",
"Arial Black", 50, false, true, 18, 8, 1, 1, 130, 800);
// Get the fill format of the word art
FillFormat wordArtFormat = wordart.getFill();
// Set the color
wordArtFormat.setOneColorGradient(Color.getRed(), 0.2, GradientStyleType.HORIZONTAL, 2);
// Set the transparency
wordArtFormat.setTransparency(0.9);
// Make the line invisible
wordart.setHasLine(false);
// Lock Shape Aspects
wordart.setLocked(true);
wordart.setLockedProperty(ShapeLockType.SELECTION, true);
wordart.setLockedProperty(ShapeLockType.SHAPE_TYPE, true);
wordart.setLockedProperty(ShapeLockType.MOVE, true);
wordart.setLockedProperty(ShapeLockType.RESIZE, true);
wordart.setLockedProperty(ShapeLockType.TEXT, true);
// Save the file
workbook.save(dataDir + "output.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Instantiate a new Workbook.
Workbook workbook = new Workbook();
// Get the first worksheet in the book.
Worksheet worksheet = workbook.getWorksheets().get(0);
// Add a new textbox to the collection.
int textboxIndex = worksheet.getTextBoxes().add(2, 1, 160, 200);
// Access your text box which is also a shape object from shapes collection
Shape shape = workbook.getWorksheets().get(0).getShapes().get(0);
// Get all the connection points in this shape
zo[] ConnectionPoints = shape.getConnectionPoints();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(MergeUnmergeRangeofCells.class);
// Create a workbook
Workbook workbook = new Workbook();
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Create a range
Range range = worksheet.getCells().createRange("A1:D4");
// Merge range into a single cell
range.merge();
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ModifyExistingSQLDataConnection.class);
// Create a workbook object from source file
Workbook workbook = new Workbook(dataDir + "DataConnection.xlsx");
// Access first Data Connection
ExternalConnection conn = workbook.getDataConnections().get(0);
// Change the Data Connection Name and Odc file
conn.setName("MyConnectionName");
conn.setOdcFile(dataDir + "MyDefaulConnection.odc");
// Change the Command Type, Command and Connection String
DBConnection dbConn = (DBConnection) conn;
dbConn.setCommandType(OLEDBCommandType.SQL_STATEMENT);
dbConn.setCommand("Select * from AdminTable");
dbConn.setConnectionInfo(
"Server=myServerAddress;Database=myDataBase;User ID=myUsername;Password=myPassword;Trusted_Connection=False");
// Save the workbook
workbook.save(dataDir + "outxput.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(ModifyExistingStyle.class) + "articles/";
/*
* Create a workbook. Open a template file. In the book1.xls file, we have applied Microsoft Excel's Named style
* i.e., "Percent" to the range "A1:C8".
*/
Workbook workbook = new Workbook(dataDir + "book1.xlsx");
// We get the Percent style and create a style object.
Style style = workbook.getNamedStyle("Percent");
// Change the number format to "0.00%".
style.setNumber(10);
// Set the font color.
style.getFont().setColor(Color.getRed());
// Update the style. so, the style of range "A1:C8" will be changed too.
style.update();
// Save the excel file.
workbook.save(dataDir + "ModifyExistingStyle_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ModifyVBAorMacroCode.class);
// Create workbook object from source Excel file
Workbook workbook = new Workbook(dataDir + "sample.xlsm");
// Change the VBA Module Code
VbaModuleCollection modules = workbook.getVbaProject().getModules();
for (int i = 0; i < modules.getCount(); i++) {
VbaModule module = modules.get(i);
String code = module.getCodes();
// Replace the original message with the modified message
if (code.contains("This is test message.")) {
code = code.replace("This is test message.", "This is Aspose.Cells message.");
module.setCodes(code);
}
}
// Save the output Excel file
workbook.save(dataDir + "output.xlsm");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(MoveRangeOfCellsInWorksheet.class);
// Instantiate the workbook object. Open the Excel file
Workbook workbook = new Workbook(dataDir + "book1.xls");
Cells cells = workbook.getWorksheets().get(0).getCells();
// Create Cell's area
CellArea ca = CellArea.createCellArea("A1", "B5");
// Move Range
cells.moveRange(ca, 0, 2);
// Save the resultant file
workbook.save(dataDir + "book2.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(PopulateDatabyRowthenColumn.class);
Workbook workbook = new Workbook();
Cells cells = workbook.getWorksheets().get(0).getCells();
cells.get("A1").setValue("data1");
cells.get("B1").setValue("data2");
cells.get("A2").setValue("data3");
cells.get("B2").setValue("data4");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(PreventExportingHiddenWorksheetContent.class);
// Create workbook object
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Do not export hidden worksheet contents
HtmlSaveOptions options = new HtmlSaveOptions();
options.setExportHiddenWorksheet(false);
// Save the workbook
workbook.save(dataDir + ".out.html");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(PrintComments.class);
// Create a workbook from source Excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Print no comments
worksheet.getPageSetup().setPrintComments(PrintCommentsType.PRINT_NO_COMMENTS);
// Print the comments as displayed on sheet
worksheet.getPageSetup().setPrintComments(PrintCommentsType.PRINT_IN_PLACE);
// Print the comments at the end of sheet
worksheet.getPageSetup().setPrintComments(PrintCommentsType.PRINT_SHEET_END);
// Save workbook in pdf format
workbook.save(dataDir + "out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(PrintingSelectedWorksheet.class);
// Instantiate a new workbook
Workbook book = new Workbook(dataDir + "Book1.xls");
// Create an object for ImageOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
// Get the first worksheet
Worksheet sheet = book.getWorksheets().get(0);
// Create a SheetRender object with respect to your desired sheet
SheetRender sr = new SheetRender(sheet, imgOptions);
// Print the worksheet
sr.toPrinter(strPrinterName);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(PrintingWholeWorkbook.class);
// Instantiate a new workbook
Workbook book = new Workbook(dataDir + "Book1.xls");
// Create an object for ImageOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
// WorkbookRender only support TIFF file format
imgOptions.setImageFormat(ImageFormat.getTiff());
// Create a WorkbookRender object with respect to your workbook
WorkbookRender wr = new WorkbookRender(book, imgOptions);
// Print the workbook
wr.toPrinter(strPrinterName);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(PropagateFormulaInTableorListObject.class) + "articles/";
// Create workbook object
Workbook book = new Workbook();
// Access first worksheet
Worksheet sheet = book.getWorksheets().get(0);
// Add column headings in cell A1 and B1
sheet.getCells().get(0, 0).putValue("Column A");
sheet.getCells().get(0, 1).putValue("Column B");
// Add list object, set its name and style
int idx = sheet.getListObjects().add(0, 0, 1, sheet.getCells().getMaxColumn(), true);
ListObject listObject = sheet.getListObjects().get(idx);
listObject.setTableStyleType(TableStyleType.TABLE_STYLE_MEDIUM_2);
listObject.setDisplayName("Table");
// Set the formula of second column so that it propagates to new rows
// automatically while entering data
listObject.getListColumns().get(1).setFormula("=[Column A] + 1");
// Save the workbook in xlsx format
book.save(dataDir + "PropagateFormulaInTable_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(ReadingAndWritingQueryTable.class);
// Create workbook from source excel file
Workbook workbook = new Workbook(dataDir + "Sample.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access first Query Table
QueryTable qt = worksheet.getQueryTables().get(0);
// Print Query Table Data
System.out.println("Adjust Column Width: " + qt.getAdjustColumnWidth());
System.out.println("Preserve Formatting: " + qt.getPreserveFormatting());
// Now set Preserve Formatting to true
qt.setPreserveFormatting(true);
// Save the workbook
workbook.save(dataDir + "Output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Create workbook from source excel file
Workbook wb = new Workbook("Query TXT.xlsx");
// Display the address(range) of result range of query table
System.out.println(wb.getWorksheets().get(0).getQueryTables().get(0).getResultRange().getAddress());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ReadLargeExcelFiles.class);
// Specify the LoadOptions
LoadOptions opt = new LoadOptions();
// Set the memory preferences
opt.setMemorySetting(MemorySetting.MEMORY_PREFERENCE);
// Instantiate the Workbook
// Load the Big Excel file having large Data set in it
Workbook wb = new Workbook(dataDir + "Book1.xlsx", opt);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RefreshCalculatePivotTablehavingCalculatedItems.class);
// Load source excel file containing a pivot table having calculated
// items
Workbook wb = new Workbook(dataDir + "sample.xlsx");
// Access first worksheet
Worksheet sheet = wb.getWorksheets().get(0);
// Change the value of cell D2
sheet.getCells().get("D2").putValue(20);
// Refresh and calculate all the pivot tables inside this sheet
for (int i = 0; i < sheet.getPivotTables().getCount(); i++) {
PivotTable pt = sheet.getPivotTables().get(i);
pt.refreshData();
pt.calculateData();
}
// Save the workbook in output pdf
wb.save(dataDir + "output.pdf", SaveFormat.PDF);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RefreshValuesOfLinkedShapes.class);
// Create workbook from source file
Workbook workbook = new Workbook(dataDir + "LinkedShape.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Change the value of cell A1
Cell cell = worksheet.getCells().get("A1");
cell.putValue(100);
// Update the value of the Linked Picture which is linked to cell A1
worksheet.getShapes().updateSelectedValue();
// Save the workbook in pdf format
workbook.save(dataDir + "output.pdf", SaveFormat.PDF);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ReleaseUnmanagedResources.class);
// Create workbook object
Workbook wb1 = new Workbook();
/*
* Call dispose method,It performs application-defined tasks associated with freeing, releasing, or resetting
* unmanaged resources.
*/
wb1.dispose();
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(RemoveUnusedStyles.class);
String inputPath = dataDir + "Styles.xlsx";
String outputPath = dataDir + "Output.xlsx";
Workbook workbook = new Workbook(inputPath);
workbook.removeUnusedStyles();
workbook.save(outputPath);
System.out.println("File saved " + outputPath);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RemoveWhitespaceAroundData.class);
// Instantiate a workbook
// Open the template file
Workbook book = new Workbook(dataDir + "book1.xlsx");
// Get the first worksheet
Worksheet sheet = book.getWorksheets().get(0);
// Specify your print area if you want
// sheet.PageSetup.PrintArea = "A1:H8";
// To remove the white border around the image.
sheet.getPageSetup().setLeftMargin(0);
sheet.getPageSetup().setRightMargin(0);
sheet.getPageSetup().setTopMargin(0);
sheet.getPageSetup().setBottomMargin(0);
// Define ImageOrPrintOptions
ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
imgOptions.setImageFormat(ImageFormat.getEmf());
// Set only one page would be rendered for the image
imgOptions.setOnePagePerSheet(true);
imgOptions.setPrintingPage(PrintingPageType.IGNORE_BLANK);
// Create the SheetRender object based on the sheet with its
// ImageOrPrintOptions attributes
SheetRender render = new SheetRender(sheet, imgOptions);
// Convert the image
render.toImage(0, dataDir + "output.emf");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RenderCustomDateFormat.class);
Workbook workbook = new Workbook(dataDir + "DateFormat.xlsx");
workbook.save(dataDir + "out.pdf");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(RenderGradientFillHTML.class) + "articles/";
//Read the source excel file having text with gradient fill
Workbook wb = new Workbook(dataDir + "sourceGradientFill.xlsx");
//Save workbook to html format
wb.save(dataDir + "out_sourceGradientFill.html");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ReleaseUnmanagedResources.class);
// Create workbook object from source file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Create empty image and fill it with blue color
int width = 800;
int height = 800;
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = image.createGraphics();
g.setColor(java.awt.Color.blue);
g.fillRect(0, 0, width, height);
// Set one page per sheet to true in image or print options
ImageOrPrintOptions opts = new ImageOrPrintOptions();
opts.setOnePagePerSheet(true);
// Render worksheet to graphics context
SheetRender sr = new SheetRender(worksheet, opts);
sr.toImage(0, g);
// Save the graphics context image in Png format
File outputfile = new File(dataDir + "test.png");
ImageIO.write(image, "png", outputfile);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ResampleImagesforExceltoPDFConversion.class);
// Initialize a new Workbook
// Open an Excel file
Workbook workbook = new Workbook(dataDir + "Book1.xlsx");
// Instantiate the PdfSaveOptions
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
// Set Image Resample properties
pdfSaveOptions.setImageResample(300, 70);
// Save the PDF file
workbook.save(dataDir + "output.pdf", pdfSaveOptions);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ResizeChartDataLabelShapeToFitText.class);
// Create an instance of Workbook containing the Chart
Workbook book = new Workbook(dataDir + "report.xlsx");
// Access the Worksheet that contains the Chart
Worksheet sheet = book.getWorksheets().get(0);
// Access ChartCollection from Worksheet
ChartCollection charts = sheet.getCharts();
// Loop over each chart in collection
for (int chartIndex = 0; chartIndex < charts.getCount(); chartIndex++) {
// Access indexed chart from the collection
Chart chart = charts.get(chartIndex);
for (int seriesIndex = 0; seriesIndex < chart.getNSeries().getCount(); seriesIndex++) {
// Access the DataLabels of indexed NSeries
DataLabels labels = chart.getNSeries().get(seriesIndex).getDataLabels();
// Set ResizeShapeToFitText property to true
labels.setResizeShapeToFitText(true);
}
// Calculate Chart
chart.calculate();
}
// Save the result
book.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RetrieveSQLConnectionData.class);
// Create a workbook object from source file
Workbook workbook = new Workbook(dataDir + "connection.xlsx");
// Access the external collections
ExternalConnectionCollection connections = workbook.getDataConnections();
int connectionCount = connections.getCount();
ExternalConnection connection = null;
for (int i = 0; i < connectionCount; i++) {
connection = connections.get(i);
// Check if the Connection is DBConnection, then retrieve its various properties
if (connection instanceof DBConnection) {
DBConnection dbConn = (DBConnection) connection;
// Retrieve DB Connection Command
System.out.println("Command: " + dbConn.getCommand());
// Retrieve DB Connection Command Type
System.out.println("Command Type: " + dbConn.getCommandType());
// Retrieve DB Connection Description
System.out.println("Description: " + dbConn.getConnectionDescription());
// Retrieve DB Connection ID
System.out.println("Id: " + dbConn.getConnectionId());
// Retrieve DB Connection Info
System.out.println("Info: " + dbConn.getConnectionInfo());
// Retrieve DB Connection Credentials
System.out.println("Credentials: " + dbConn.getCredentials());
// Retrieve DB Connection Name
System.out.println("Name: " + dbConn.getName());
// Retrieve DB Connection ODC File
System.out.println("OdcFile: " + dbConn.getOdcFile());
// Retrieve DB Connection Source File
System.out.println("Source file: " + dbConn.getSourceFile());
// Retrieve DB Connection Type
System.out.println("Type: " + dbConn.getType());
// Retrieve DB Connection Parameters Collection
ConnectionParameterCollection parameterCollection = dbConn.getParameters();
int paramCount = parameterCollection.getCount();
// Iterate the Parameter Collection
for (int j = 0; j < paramCount; j++) {
ConnectionParameter param = parameterCollection.get(j);
// Retrieve Parameter Cell Reference
System.out.println("Cell reference: " + param.getCellReference());
// Retrieve Parameter Name
System.out.println("Parameter name: " + param.getName());
// Retrieve Parameter Prompt
System.out.println("Prompt: " + param.getPrompt());
// Retrieve Parameter SQL Type
System.out.println("SQL Type: " + param.getSqlType());
// Retrieve Parameter Type
System.out.println("Param Type: " + param.getType());
// Retrieve Parameter Value
System.out.println("Param Value: " + param.getValue());
} // End for
} // End if
} // End for
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RetrievingExternalDataSourcesDetails.class);
// Open the template Excel file
Workbook workbook = new Workbook(dataDir + "connection.xlsx");
// Get the external data connections
ExternalConnectionCollection connections = workbook.getDataConnections();
// Get the count of the collection connection
int connectionCount = connections.getCount();
// Create an external connection object
ExternalConnection connection = null;
// Loop through all the connections in the file
for (int i = 0; i < connectionCount; i++) {
connection = connections.get(i);
if (connection instanceof DBConnection) {
// Instantiate the DB Connection
DBConnection dbConn = (DBConnection) connection;
// Print the complete details of the object
System.out.println("Command: " + dbConn.getCommand());
System.out.println("Command Type: " + dbConn.getCommandType());
System.out.println("Description: " + dbConn.getConnectionDescription());
System.out.println("Id: " + dbConn.getConnectionId());
System.out.println("Info: " + dbConn.getConnectionInfo());
System.out.println("Credentials: " + dbConn.getCredentials());
System.out.println("Name: " + dbConn.getName());
System.out.println("OdcFile: " + dbConn.getOdcFile());
System.out.println("Source file: " + dbConn.getSourceFile());
System.out.println("Type: " + dbConn.getType());
// Get the parameters collection (if the connection object has)
ConnectionParameterCollection parameterCollection = dbConn.getParameters();
// Loop through all the parameters and obtain the details
int paramCount = parameterCollection.getCount();
for (int j = 0; j < paramCount; j++) {
ConnectionParameter param = parameterCollection.get(j);
System.out.println("Cell reference: " + param.getCellReference());
System.out.println("Parameter name: " + param.getName());
System.out.println("Prompt: " + param.getPrompt());
System.out.println("SQL Type: " + param.getSqlType());
System.out.println("Param Type: " + param.getType());
System.out.println("Param Value: " + param.getValue());
}
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ReturningRangeOfValues.class);
Workbook wb = new Workbook();
Cells cells = wb.getWorksheets().get(0).getCells();
Cell cell = cells.get(0, 0);
cell.setArrayFormula("=MYFUNC()", 2, 2);
Style style = cell.getStyle();
style.setNumber(14);
cell.setStyle(style);
CalculationOptions copt = new CalculationOptions();
copt.setCustomFunction(new CustomFunctionStaticValue());
wb.calculateFormula(copt);
// Save to xlsx by setting the calc mode to manual
wb.getSettings().setCalcMode(CalcModeType.MANUAL);
wb.save(dataDir + "output.xlsx");
// Save to pdf
wb.save(dataDir + "output.pdf");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ReuseStyleObjects.class);
// Create an instance of Workbook & load an existing spreadsheet
Workbook workbook = new Workbook(dataDir + "Book1.xls");
// Retrieve the Cell Collection of the first Worksheet
Cells cells = workbook.getWorksheets().get(0).getCells();
// Create an instance of Style and add it to the pool of styles
Style styleObject = workbook.createStyle();
// Retrieve the Font object of newly created style
Font font = styleObject.getFont();
// Set the font color to Red
font.setColor(Color.getRed());
// Set the newly created style on two different cells
cells.get("A1").setStyle(styleObject);
cells.get("A2").setStyle(styleObject);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(RichTextCustomData.class);
// Create a workbook from source Excel file
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the first chart inside the sheet
Chart chart = worksheet.getCharts().get(0);
// Access the data label of first series first point
DataLabels dlbls = chart.getNSeries().get(0).getPoints().get(0).getDataLabels();
// Set data label text
dlbls.setText("Rich Text Label");
// Set the font setting of the first 10 characters
FontSetting fntSetting = dlbls.characters(0, 10);
fntSetting.getFont().setColor(Color.getRed());
fntSetting.getFont().setBold(true);
// Save the workbook
workbook.save("output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(RowsIterator.class);
// Load a file in an instance of Workbook
Workbook book = new Workbook(dataDir + "sample.xlsx");
// Get the iterator for RowCollection
Iterator rowsIterator = book.getWorksheets().get(0).getCells().getRows().iterator();
// Traverse rows in the collection
while (rowsIterator.hasNext()) {
Row row = (Row) rowsIterator.next();
System.out.println(row.getIndex());
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SaveEachWorksheettoDifferentPDF.class);
// Instantiate a new workbook and open the Excel
// File from its location
Workbook workbook = new Workbook(dataDir + "input.xlsx");
// Get the count of the worksheets in the workbook
int sheetCount = workbook.getWorksheets().getCount();
// Make all sheets invisible except first worksheet
for (int i = 1; i < workbook.getWorksheets().getCount(); i++) {
workbook.getWorksheets().get(i).setVisible(false);
}
// Take Pdfs of each sheet
for (int j = 0; j < workbook.getWorksheets().getCount(); j++) {
Worksheet ws = workbook.getWorksheets().get(j);
workbook.save(dataDir + "_" + ws.getName() + ".pdf");
if (j < workbook.getWorksheets().getCount() - 1) {
workbook.getWorksheets().get(j + 1).setVisible(true);
workbook.getWorksheets().get(j).setVisible(false);
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(SaveExcelToPDF.class);
// Load excel file into workbook object
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
// Save into Pdf with Minimum size
PdfSaveOptions opts = new PdfSaveOptions();
opts.setOptimizationType(PdfOptimizationType.MINIMUM_SIZE);
workbook.save(dataDir + "output.pdf", opts);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SaveODSfile.class);
// Create workbook
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Put some value in cell A1
Cell cell = worksheet.getCells().get("A1");
cell.putValue("Welcome to Aspose!");
// Save ODS in ODF 1.2 version which is default
OdsSaveOptions options = new OdsSaveOptions();
workbook.save("ODF1.2.ods", options);
// Save ODS in ODF 1.1 version
options.setStrictSchema11(true);
workbook.save("ODF1.1.ods", options);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(SearchDataUsingOriginalValues.class);
// Create workbook object
Workbook workbook = new Workbook();
// Access first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Add 10 in cell A1 and A2
worksheet.getCells().get("A1").putValue(10);
worksheet.getCells().get("A2").putValue(10);
// Add Sum formula in cell D4 but customize it as ---
Cell cell = worksheet.getCells().get("D4");
Style style = cell.getStyle();
style.setCustom("---");
cell.setStyle(style);
// The result of formula will be 20, but 20 will not be visible because the cell is formated as ---
cell.setFormula("=Sum(A1:A2)");
// Calculate the workbook
workbook.calculateFormula();
// Create find options, we will search 20 using. original values otherwise 20 will never be found,because it is formatted
// as
FindOptions options = new FindOptions();
options.setLookInType(LookInType.ORIGINAL_VALUES);
options.setLookAtType(LookAtType.ENTIRE_CONTENT);
Cell foundCell = null;
Object obj = 20;
// Find 20 which is Sum(A1:A2) and formatted as ---
foundCell = worksheet.getCells().find(obj, foundCell, options);
// Print the found cell
System.out.println(foundCell);
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SearchReplaceDataInRange.class);
Workbook workbook = new Workbook(dataDir + "input.xlsx");
Worksheet worksheet = workbook.getWorksheets().get(0);
// Specify the range where you want to search
// Here the range is E3:H6
CellArea area = CellArea.createCellArea("E3", "H6");
// Specify Find options
FindOptions opts = new FindOptions();
opts.setLookInType(LookInType.VALUES);
opts.setLookAtType(LookAtType.ENTIRE_CONTENT);
opts.setRange(area);
Cell cell = null;
do {
// Search the cell with value search within range
cell = worksheet.getCells().find("search", cell, opts);
// If no such cell found, then break the loop
if (cell == null)
break;
// Replace the cell with value replace
cell.putValue("replace");
} while (true);
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SecurePDFDocuments.class);
// Open an Excel file
Workbook workbook = new Workbook(dataDir + "input.xlsx");
// Instantiate PDFSaveOptions to manage security attributes
PdfSaveOptions saveOption = new PdfSaveOptions();
saveOption.setSecurityOptions(new PdfSecurityOptions());
// Set the user password
saveOption.getSecurityOptions().setUserPassword("user");
// Set the owner password
saveOption.getSecurityOptions().setOwnerPassword("owner");
// Disable extracting content permission
saveOption.getSecurityOptions().setExtractContentPermission(false);
// Disable print permission
saveOption.getSecurityOptions().setPrintPermission(false);
// Save the PDF document with encrypted settings
workbook.save(dataDir + "securepdf_test.pdf", saveOption);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SetAutoRecoverProperty.class);
// Create workbook object
Workbook workbook = new Workbook();
// Read AutoRecover property
System.out.println("AutoRecover: " + workbook.getSettings().getAutoRecover());
// Set AutoRecover property to false
workbook.getSettings().setAutoRecover(false);
// Save the workbook
workbook.save("output.xlsx");
// Read the saved workbook again
workbook = new Workbook("output.xlsx");
// Read AutoRecover property
System.out.println("AutoRecover: " + workbook.getSettings().getAutoRecover());
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SetBackgroundPictureforWorksheet.class) + "articles/";
// Instantiate a new Workbook.
Workbook workbook = new Workbook();
// Get the first worksheet.
Worksheet sheet = workbook.getWorksheets().get(0);
// Get the image file.
File file = new File(dataDir + "school.jpg");
// Get the picture into the streams.
byte[] imageData = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(imageData);
// Set the background image for the sheet.
sheet.setBackgroundImage(imageData);
// Save the excel file
workbook.save(dataDir + "SBPforWorksheet.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SetCustomFontFolders.class);
// Defining string variables to store paths to font folders & font file
String fontFolder1 = dataDir + "/Arial";
String fontFolder2 = dataDir + "/Calibri";
String fontFile = dataDir + "/Arial/arial.ttf";
// Setting first font folder with setFontFolder method
// Second parameter directs the API to search the sub folders for font files
FontConfigs.setFontFolder(fontFolder1, true);
// Setting both font folders with setFontFolders method
// Second parameter prohibits the API to search the sub folders for font files
FontConfigs.setFontFolders(new String[] { fontFolder1, fontFolder2 }, false);
// Defining FolderFontSource
FolderFontSource sourceFolder = new FolderFontSource(fontFolder1, false);
// Defining FileFontSource
FileFontSource sourceFile = new FileFontSource(fontFile);
// Defining MemoryFontSource
byte[] bytes = Files.readAllBytes(new File(fontFile).toPath());
MemoryFontSource sourceMemory = new MemoryFontSource(bytes);
// Setting font sources
FontConfigs.setFontSources(new FontSourceBase[] { sourceFolder, sourceFile, sourceMemory });
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(SetExternalLinksInFormulas.class);
// Instantiate a new Workbook.
Workbook workbook = new Workbook();
// Get first Worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Get Cells collection
Cells cells = sheet.getCells();
// Set formula with external links
cells.get("A1").setFormula("=SUM('[F:\\book1.xls]Sheet1'!A2, '[F:\\book1.xls]Sheet1'!A4)");
// Set formula with external links
cells.get("A2").setFormula("='[F:\\book1.xls]Sheet1'!A8");
// Save the workbook
workbook.save(dataDir + "output.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SetFormulaCalculationMode.class);
// Create a workbook
Workbook workbook = new Workbook();
// Set the Formula Calculation Mode to Manual
workbook.getSettings().setCalcMode(CalcModeType.MANUAL);
// Save the workbook
workbook.save("output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SetLineSpacingofParagraph.class);
// Create a workbook
Workbook wb = new Workbook();
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Add text box inside the sheet
ws.getShapes().addShape(MsoDrawingType.TEXT_BOX, 2, 0, 2, 0, 100, 200);
// Access first shape which is a text box and set is text
Shape shape = ws.getShapes().get(0);
shape.setText("Sign up for your free phone number.\nCall and text online for free.");
// Acccess the first paragraph
TextParagraph p = shape.getTextBody().getTextParagraphs().get(1);
// Set the line space
p.setLineSpaceSizeType(LineSpaceSizeType.POINTS);
p.setLineSpace(20);
// Set the space after
p.setSpaceAfterSizeType(LineSpaceSizeType.POINTS);
p.setSpaceAfter(10);
// Set the space before
p.setSpaceBeforeSizeType(LineSpaceSizeType.POINTS);
p.setSpaceBefore(10);
// Save the workbook in xlsx format
wb.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SetPictureAsBackgroundFillInChart.class);
// Create a new Workbook.
Workbook workbook = new Workbook();
// Get the first worksheet.
Worksheet sheet = workbook.getWorksheets().get(0);
// Set the name of worksheet
sheet.setName("Data");
// Get the cells collection in the sheet.
Cells cells = workbook.getWorksheets().get(0).getCells();
// Put some values into a cells of the Data sheet.
cells.get("A1").putValue("Region");
cells.get("A2").putValue("France");
cells.get("A3").putValue("Germany");
cells.get("A4").putValue("England");
cells.get("A5").putValue("Sweden");
cells.get("A6").putValue("Italy");
cells.get("A7").putValue("Spain");
cells.get("A8").putValue("Portugal");
cells.get("B1").putValue("Sale");
cells.get("B2").putValue(70000);
cells.get("B3").putValue(55000);
cells.get("B4").putValue(30000);
cells.get("B5").putValue(40000);
cells.get("B6").putValue(35000);
cells.get("B7").putValue(32000);
cells.get("B8").putValue(10000);
// Add a chart sheet.
int sheetIndex = workbook.getWorksheets().add(SheetType.CHART);
sheet = workbook.getWorksheets().get(sheetIndex);
// Set the name of worksheet
sheet.setName("Chart");
// Create chart
int chartIndex = 0;
chartIndex = sheet.getCharts().add(ChartType.COLUMN, 1, 1, 25, 10);
Chart chart = sheet.getCharts().get(chartIndex);
// Set some properties of chart plot area. To set a picture as fill format and make the border invisible.
File file = new File(dataDir + "aspose-logo.png");
byte[] data = new byte[(int) file.length()];
FileInputStream fis = new FileInputStream(file);
fis.read(data);
chart.getPlotArea().getArea().getFillFormat().setImageData(data);
chart.getPlotArea().getBorder().setVisible(false);
// Set properties of chart title
chart.getTitle().setText("Sales By Region");
chart.getTitle().getFont().setColor(Color.getBlue());
chart.getTitle().getFont().setBold(true);
chart.getTitle().getFont().setSize(12);
// Set properties of nseries
chart.getNSeries().add("Data!B2:B8", true);
chart.getNSeries().setCategoryData("Data!A2:A8");
chart.getNSeries().setColorVaried(true);
// Set the Legend.
Legend legend = chart.getLegend();
legend.setPosition(LegendPositionType.TOP);
// Save the excel file
workbook.save(dataDir + "column_chart.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SetPresetWordArtStyle.class) + "articles/";
//Create workbook object
Workbook wb = new Workbook();
//Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
//Create a textbox with some text
int idx = ws.getTextBoxes().add(0, 0, 100, 700);
TextBox tb = ws.getTextBoxes().get(idx);
tb.setText("Aspose File Format APIs");
tb.getFont().setSize(44);
//Sets preset WordArt style to the text of the shape.
ArrayList<FontSetting> aList = tb.getCharacters();
FontSetting fntSetting = aList.get(0);
fntSetting.setWordArtStyle(PresetWordArtStyle.WORD_ART_STYLE_3);
//Save the workbook in xlsx format
wb.save(dataDir + "SetPresetWordArtStyle_out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(Settextofchartlegend.class);
// Open the template file.
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
// Access the first worksheet
Worksheet sheet = workbook.getWorksheets().get(0);
// Access the first chart inside the sheet
Chart chart = sheet.getCharts().get(0);
// Set text of second legend entry fill to none
chart.getLegend().getLegendEntries().get(1).setTextNoFill(true);
// Save the workbook in xlsx format
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettheCommentofTableorListObject.class);
// Open the template file.
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access first worksheet.
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access first list object or table.
ListObject lstObj = worksheet.getListObjects().get(0);
// Set the comment of the list object
lstObj.setComment("This is Aspose.Cells comment.");
// Save the workbook in xlsx format
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingPageSetupOptions.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "CustomerReport.xls");
// Accessing the first worksheet in the Excel file
Worksheet sheet = workbook.getWorksheets().get(0);
PageSetup pageSetup = sheet.getPageSetup();
// Setting the orientation to Portrait
pageSetup.setOrientation(PageOrientationType.PORTRAIT);
// Setting the scaling factor to 100
// pageSetup.setZoom(100);
// OR Alternately you can use Fit to Page Options as under
// Setting the number of pages to which the length of the worksheet will be spanned
pageSetup.setFitToPagesTall(1);
// Setting the number of pages to which the width of the worksheet will be spanned
pageSetup.setFitToPagesWide(1);
// Setting the paper size to A4
pageSetup.setPaperSize(PaperSizeType.PAPER_A_4);
// Setting the print quality of the worksheet to 1200 dpi
pageSetup.setPrintQuality(1200);
// Setting the first page number of the worksheet pages
pageSetup.setFirstPageNumber(2);
// Save the workbook
workbook.save(dataDir + "PageSetup.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingPivotTableOption.class);
Workbook wb = new Workbook(dataDir + "input.xlsx");
PivotTable pt = wb.getWorksheets().get(0).getPivotTables().get(0);
// Indicating if or not display the empty cell value
pt.setDisplayNullString(true);
// Indicating the null string
pt.setNullString("null");
pt.calculateData();
pt.setRefreshDataOnOpeningFile(false);
wb.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SettingPrintoptions.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "PageSetup.xls");
// Accessing the first worksheet in the Excel file
Worksheet sheet = workbook.getWorksheets().get(0);
PageSetup pageSetup = sheet.getPageSetup();
// Specifying the cells range (from A1 cell to E30 cell) of the print area
pageSetup.setPrintArea("A1:E30");
// Defining column numbers A & E as title columns
pageSetup.setPrintTitleColumns("$A:$E");
// Defining row numbers 1 & 2 as title rows
pageSetup.setPrintTitleRows("$1:$2");
// Allowing to print gridlines
pageSetup.setPrintGridlines(true);
// Allowing to print row/column headings
pageSetup.setPrintHeadings(true);
// Allowing to print worksheet in black & white mode
pageSetup.setBlackAndWhite(true);
// Allowing to print comments as displayed on worksheet
pageSetup.setPrintComments(PrintCommentsType.PRINT_IN_PLACE);
// Allowing to print worksheet with draft quality
pageSetup.setPrintDraft(true);
// Allowing to print cell errors as N/A
pageSetup.setPrintErrors(PrintErrorsType.PRINT_ERRORS_NA);
// Setting the printing order of the pages to over then down
pageSetup.setOrder(PrintOrderType.OVER_THEN_DOWN);
// Save the workbook
workbook.save(dataDir + "PageSetup_Print.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SettingScaleCropLinksUpToDate.class) + "articles/";
// Create workbook
Workbook wb = new Workbook();
// Setting ScaleCrop and LinksUpToDate BuiltInDocumentProperties
wb.getBuiltInDocumentProperties().setScaleCrop(true);
wb.getBuiltInDocumentProperties().setLinksUpToDate(true);
// Save output excel file
wb.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(SettingSharedFormula.class);
String filePath = dataDir + "input.xlsx";
// Instantiate a Workbook from existing file
Workbook workbook = new Workbook(filePath);
// Get the cells collection in the first worksheet
Cells cells = workbook.getWorksheets().get(0).getCells();
// Apply the shared formula in the range i.e.., B2:B14
cells.get("B2").setSharedFormula("=A2*0.09", 13, 1);
// Save the excel file
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getSharedDataDir(SettingTextEffectsShadowOfShapeOrTextbox.class) + "articles/";
// Create workbook object
Workbook wb = new Workbook();
// Access first worksheet
Worksheet ws = wb.getWorksheets().get(0);
// Add text box with these dimensions
int idx = ws.getTextBoxes().add(2, 2, 100, 400);
TextBox tb = ws.getTextBoxes().get(idx);
// Set the text of the textbox
tb.setText("This text has the following settings.\n\nText Effects > Shadow > Offset Bottom");
// Set all the text runs shadow to preset offset bottom
for (int i = 0; i < tb.getTextBody().getCount(); i++) {
tb.getTextBody().get(i).getTextOptions().getShadow().setPresetType(PresetShadowType.OFFSET_BOTTOM);
}
// Set the font color and size of the textbox
tb.getFont().setColor(Color.getRed());
tb.getFont().setSize(16);
// Save the output file
wb.save(dataDir + "STESOfShapeOrTextbox_out.xlsx", SaveFormat.XLSX);
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SetWorksheetTabColor.class);
// Instantiate a new Workbook
Workbook workbook = new Workbook(dataDir + "Book1.xls");
// Get the first worksheet in the book
Worksheet worksheet = workbook.getWorksheets().get(0);
// Set the tab color
worksheet.setTabColor(Color.getRed());
// Save the Excel file
workbook.save(dataDir + "worksheettabcolor.xls");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ShowCellRangeAsTheDataLabels.class);
// Create workbook from the source Excel file
Workbook workbook = new Workbook(dataDir + "sample.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Access the chart inside the worksheet
Chart chart = worksheet.getCharts().get(0);
// Check the "Label Contains - Value From Cells"
DataLabels dataLabels = chart.getNSeries().get(0).getDataLabels();
dataLabels.setShowCellRange(true);
// Save the workbook
workbook.save(dataDir + "output.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(ShowFormulas.class);
// Load the source workbook
Workbook workbook = new Workbook(dataDir + "source.xlsx");
// Access the first worksheet
Worksheet worksheet = workbook.getWorksheets().get(0);
// Show formulas of the worksheet
worksheet.setShowFormulas(true);
// Save the workbook
workbook.save(dataDir + "out.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the documents directory.
String dataDir = Utils.getDataDir(SigningSpreadsheets.class);
// Create an instance of DigitalSignatureCollection
DigitalSignatureCollection signatures = new DigitalSignatureCollection();
// Load the certificate into an instance of InputStream
InputStream inStream = new FileInputStream("d:/temp.pfx");
// Create an instance of KeyStore with PKCS12 cryptography
KeyStore inputKeyStore = KeyStore.getInstance("PKCS12");
// Use the KeyStore.load method to load the certificate stream and its password
inputKeyStore.load(inStream, KEYSTORE_PASSWORD.toCharArray());
// Create an instance of DigitalSignature and pass the instance of KeyStore, password, comments and time
DigitalSignature signature = new DigitalSignature(inputKeyStore, KEYSTORE_PASSWORD, "test for sign",
DateTime.getNow());
// Add the instance of DigitalSignature into the collection
signatures.add(signature);
// Load an existing spreadsheet using the Workbook class
Workbook workbook = new Workbook(dataDir + "unsigned.xlsx");
// Set the signature
workbook.setDigitalSignature(signatures);
// Save the signed spreadsheet
workbook.save(dataDir + "signed.xlsx");
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public class SmartMarkerCallBack implements ISmartMarkerCallBack {
Workbook workbook;
SmartMarkerCallBack(Workbook workbook) {
this.workbook = workbook;
}
@Override
public void process(int sheetIndex, int rowIndex, int colIndex, String tableName, String columnName) {
System.out.println("Processing Cell : " + workbook.getWorksheets().get(sheetIndex).getName() + "!"
+ CellsHelper.cellIndexToName(rowIndex, colIndex));
System.out.println("Processing Marker : " + tableName + "." + columnName);
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
public static void main(String[] args) throws Exception {
// The path to the documents directory.
String dataDir = Utils.getDataDir(SmartMarkerGroupingImage.class);
SmartMarkerGroupingImage grouping = new SmartMarkerGroupingImage();
grouping.Execute(dataDir);
}
public void Execute(String dataDir) throws Exception {
// Get the image
Path path = Paths.get(dataDir + "sample1.png");
byte[] photo1 = Files.readAllBytes(path);
// Get the image
path = Paths.get(dataDir + "sample2.jpg");
byte[] photo2 = Files.readAllBytes(path);
// Create a new workbook and access its worksheet
Workbook workbook = new Workbook();
Worksheet worksheet = workbook.getWorksheets().get(0);
// Set the standard row height to 35
worksheet.getCells().setStandardHeight(35);
// Set column widhts of D, E and F
worksheet.getCells().setColumnWidth(3, 20);
worksheet.getCells().setColumnWidth(4, 20);
worksheet.getCells().setColumnWidth(5, 40);
// Add the headings in columns D, E and F
worksheet.getCells().get("D1").putValue("Name");
Style st = worksheet.getCells().get("D1").getStyle();
st.getFont().setBold(true);
worksheet.getCells().get("D1").setStyle(st);
worksheet.getCells().get("E1").putValue("City");
worksheet.getCells().get("E1").setStyle(st);
worksheet.getCells().get("F1").putValue("Photo");
worksheet.getCells().get("F1").setStyle(st);
// Add smart marker tags in columns D, E, F
worksheet.getCells().get("D2").putValue("&=Person.Name(group:normal,skip:1)");
worksheet.getCells().get("E2").putValue("&=Person.City");
worksheet.getCells().get("F2").putValue("&=Person.Photo(Picture:FitToCell)");
// Create Persons objects with photos
ArrayList<Person> persons = new ArrayList<Person>();
persons.add(new Person("George", "New York", photo1));
persons.add(new Person("George", "New York", photo2));
persons.add(new Person("George", "New York", photo1));
persons.add(new Person("George", "New York", photo2));
persons.add(new Person("Johnson", "London", photo2));
persons.add(new Person("Johnson", "London", photo1));
persons.add(new Person("Johnson", "London", photo2));
persons.add(new Person("Simon", "Paris", photo1));
persons.add(new Person("Simon", "Paris", photo2));
persons.add(new Person("Simon", "Paris", photo1));
persons.add(new Person("Henry", "Sydney", photo2));
persons.add(new Person("Henry", "Sydney", photo1));
persons.add(new Person("Henry", "Sydney", photo2));
// Create a workbook designer
WorkbookDesigner designer = new WorkbookDesigner(workbook);
// Set the data source and process smart marker tags
designer.setDataSource("Person", persons);
designer.process();
// Save the workbook
workbook.save(dataDir + "output.xlsx", SaveFormat.XLSX);
System.out.println("File saved");
}
public class Person {
// Create Name, City and Photo properties
private String m_Name;
private String m_City;
private byte[] m_Photo;
public Person(String name, String city, byte[] photo) {
m_Name = name;
m_City = city;
m_Photo = photo;
}
public String getName() {
return this.m_Name;
}
public void setName(String name) {
this.m_Name = name;
}
public String getCity() {
return this.m_City;
}
public void setCity(String address) {
this.m_City = address;
}
public byte[] getPhoto() {
return this.m_Photo;
}
public void setAddress(byte[] photo) {
this.m_Photo = photo;
}
}
// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
String dataDir = Utils.getDataDir(SortData.class);
// Instantiating a Workbook object
Workbook workbook = new Workbook(dataDir + "Book_SourceData.xls");
// Accessing the first worksheet in the Excel file
Worksheet worksheet = workbook.getWorksheets().get(0);
// Get the cells collection in the sheet
Cells cells = worksheet.getCells();
// Obtain the DataSorter object in the workbook
DataSorter sorter = workbook.getDataSorter();
// Set the first order
sorter.setOrder1(SortOrder.ASCENDING);
// Define the first key.
sorter.setKey1(0);
// Set the second order
sorter.setOrder2(SortOrder.ASCENDING);
// Define the second key
sorter.setKey2(1);
// Create a cells area (range).
CellArea ca = new CellArea();
// Specify the start row index.
ca.StartRow = 1;
// Specify the start column index.
ca.StartColumn = 0;
// Specify the last row index.
ca.EndRow = 9;
// Specify the last column index.
ca.EndColumn = 2;
// Sort data in the specified data range (A2:C10)
sorter.sort(cells, ca);
// Saving the excel file
workbook.save(dataDir + "outBook_SortedData.xls");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment