В этом кратком руководстве вы узнаете, как вставить таблицу в слайд с помощью Java. В нем содержится информация, необходимая для настройки среды IDE для написания приложения, а также подробные шаги для выполнения этой задачи. В итоге вы получите исполняемый образец кода, демонстрирующий, как создать таблицу в PowerPoint с помощью Java и сохранить результирующую презентацию на диске как PPTX, PPT или в любом другом формате. поддерживаемый формат без установки MS PowerPoint или любого другого стороннего инструмента.
Шаги по добавлению таблицы в PowerPoint с помощью Java
- Настройте IDE на использование Aspose.Slides для вставки таблицы.
- Создайте новую презентацию с помощью класса Presentation и получите доступ к первому слайду
- Добавьте новую таблицу на выбранный слайд, используя метод addTable() и указав положение текста, а также высоту и ширину ячеек.
- Перебрать все строки и установить текст вместе с настройками шрифта.
- Сохраните презентацию на диск с таблицей
Вышеупомянутые шаги объясняют как создавать таблицы в PowerPoint с помощью Java. Выявляются все необходимые классы и методы, необходимые для выполнения поставленной задачи. Процесс прост: на слайд добавляется таблица, а затем ее ячейки заполняются образцом текста.
Код для создания таблицы в PowerPoint с использованием Java
/* | |
* To change this license header, choose License Headers in Project Properties. | |
* To change this template file, choose Tools | Templates | |
* and open the template in the editor. | |
*/ | |
package testslides; | |
import com.aspose.slides.BulletType; | |
import com.aspose.slides.ICell; | |
import com.aspose.slides.IRow; | |
import com.aspose.slides.ISlide; | |
import com.aspose.slides.ITable; | |
import com.aspose.slides.ITextFrame; | |
import com.aspose.slides.License; | |
import com.aspose.slides.Presentation; | |
public class AddTable { | |
public static void main(String[] args) throws Exception {//handle exception during adding any tablle | |
String path = "/Users/mudassirkhan/Documents/KnowledgeBase/TestData/"; | |
// Load the product license to create a table | |
License slidesTablelic = new License(); | |
slidesTablelic.setLicense(path + "Conholdate.Total.Product.Family.lic"); | |
// Create a new presentation | |
Presentation presentationForTable = new Presentation(); | |
// Access the first slide in the presentation | |
ISlide slide = presentationForTable.getSlides().get_Item(0); | |
// Define the arrays containing column widths and row heights | |
double[] dColumnsWidths = { 55, 55, 55 }; | |
double[] dRowsHeights = { 55, 36, 36, 36, 36 }; | |
// Add a new table with desired rows and columns | |
ITable newTable = slide.getShapes().addTable(60, 60, dColumnsWidths, dRowsHeights); | |
// Traverse through all the rows | |
for (IRow tableRow : newTable.getRows()) | |
{ | |
// Traverse through all the cells in the current row | |
for (ICell tableCell : tableRow) | |
{ | |
// Access the respective text frame of the cell | |
ITextFrame txtFormat = tableCell.getTextFrame(); | |
// Add some text to the cell | |
int iFirstRowIndex = tableCell.getFirstRowIndex(); | |
int iFirstColumnIndex = tableCell.getFirstColumnIndex(); | |
txtFormat.setText( "Text " + iFirstRowIndex + " " + iFirstColumnIndex); | |
// Set the font related property for the newly added text | |
txtFormat.getParagraphs().get_Item(0).getPortions().get_Item(0).getPortionFormat().setFontHeight(10); | |
txtFormat.getParagraphs().get_Item(0).getParagraphFormat().getBullet().setType(BulletType.None); | |
} | |
} | |
// Save the presentation with table | |
presentationForTable.save("PresentationTable.pptx", com.aspose.slides.SaveFormat.Pptx); | |
System.out.println("Done"); | |
} | |
} |
Этот код демонстрирует как создать таблицу в PowerPoint с помощью Java. Несколько классов интерфейса используются для использования различных функций, например, ISlide используется для доступа к слайду, класс ITable используется для работы с таблицами, а классы IRow и ICell используются для работы с отдельными ячейками. Класс ITextFrame — это основной интерфейс, который используется для установки текста в ячейке и установки форматирования ячеек.
Этот урок научил нас как сделать таблицу в презентации PowerPoint с помощью Java. Если вы хотите изучить процесс создания HTML из презентации, обратитесь к статье как создавать слайды PowerPoint в HTML с помощью Java.