さまざまな形式のファイルを開く

Excelファイルを開く簡単な方法

ファイルのパスを通じて開く

ファイルパスを使用してMicrosoft Excelファイルを開くには、ファイルパスをパラメーターとして渡してWorkbookクラスのインスタンスを作成します。次のサンプルコードは、ファイルパスを使用してExcelファイルを開く方法を示しています。

// 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(OpeningFilesThroughPath.class) + "files/";
// Opening from path.
// Creating an Workbook object with an Excel file path
Workbook workbook1 = new Workbook(dataDir + "Book1.xlsx");
// Print message
System.out.println("Workbook opened using path successfully.");

ストリームを介した開く

必要なExcelファイルがストリームとして保存されている場合、ファイルパスを使用してファイルを開く方法と同様に、Workbookクラスのインスタンスを作成する際にストリームをパラメーターとして渡します。次のサンプルコードは、ストリームを使用してExcelファイルを開く方法を示しています。

// 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(OpeningFilesThroughStream.class) + "loading_saving/";
// Opening workbook from stream
// Create a Stream object
FileInputStream fstream = new FileInputStream(dataDir + "Book2.xls");
// Creating an Workbook object with the stream object
Workbook workbook2 = new Workbook(fstream);
fstream.close();
// Print message
System.out.println("Workbook opened using stream successfully.");

異なるMicrosoft Excelバージョンのファイルを開く

ユーザーはLoadOptionsクラスを使用してExcelファイルのフォーマットを指定することができます。その際にはLoadFormat列挙型を使用します。

LoadFormat列挙型には、多くの事前定義ファイル形式が含まれています。 以下にその一部を示します。

フォーマットの種類 説明
Csv はCSVファイルを表します
Excel97To2003 はExcel 97-2003ファイルを表します
Xlsx はExcel 2007/2010/2013/2016/2019およびOffice 365 XLSXファイルを表します
Xlsm はExcel 2007/2010/2013/2016/2019およびOffice 365 XLSMファイルを表します
Xltx はExcel 2007/2010/2013/2016/2019およびOffice 365テンプレートXLTXファイルを表します
Xltm はExcel 2007/2010/2013/2016/2019およびOffice 365マクロ有効なXLTMファイルを表します
Xlsb はExcel 2007/2010/2013/2016/2019およびOffice 365バイナリXLSBファイルを表します
SpreadsheetML はSpreadsheetMLファイルを表します
Tsv はタブ区切りの値ファイルを表します
TabDelimited はタブ区切りのテキストファイルを表します
Ods はODSファイルを表します
Html はHTMLファイルを表します
Mhtml はMHTMLファイルを表します

Microsoft Excel 95/5.0 ファイルを開く

Microsoft Excel 95ファイルを開くには、Workbookインスタンスをパスまたはテンプレートファイルのストリームでインスタンス化します。コードのテストに使用するサンプルファイルは、次のリンクからダウンロードできます。

Excel95_5.0.xls

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// Opening Microsoft Excel 97 Files
// Creating an EXCEL_97_TO_2003 LoadOptions object
// Creating an Workbook object with excel 97 file path and the
// loadOptions object
new Workbook(srcDir + "Excel95_5.0.xls");

Microsoft Excel 97またはそれ以降のバージョンXLSファイルの開閉

Microsoft Excel XLS 97またはそれ以降のバージョンのXLSファイルを開くには、Workbookインスタンスをパスまたはテンプレートファイルのストリームでインスタンス化します。または、LoadOptionsメソッドを使用してLoadFormat列挙型のEXCEL_97_TO_2003値を選択します。

// 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(OpeningMicrosoftExcel972003Files.class) + "loading_saving/";
// Opening Microsoft Excel 97 Files
// Createing and EXCEL_97_TO_2003 LoadOptions object
LoadOptions loadOptions1 = new LoadOptions(LoadFormat.EXCEL_97_TO_2003);
// Creating an Workbook object with excel 97 file path and the
// loadOptions object
Workbook workbook3 = new Workbook(dataDir + "Book_Excel97_2003.xls", loadOptions1);
// Print message
System.out.println("Excel 97 Workbook opened successfully.");

Microsoft Excel 2007またはそれ以降のバージョンXLSXファイルの開閉

Microsoft Excel 2007またはそれ以降のバージョンのXLSXファイルを開くには、Workbookインスタンスをパスまたはテンプレートファイルのストリームでインスタンス化します。または、LoadOptionsクラスを使用してLoadFormat列挙型の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(OpeningMicrosoftExcel2007XlsxFiles.class) + "loading_saving/";
// Opening Microsoft Excel 2007 XLSX Files. Createing and XLSX LoadOptions object
LoadOptions loadOptions2 = new LoadOptions(LoadFormat.XLSX);
// Creating an Workbook object with 2007 xlsx file path and the loadOptions object
Workbook workbook4 = new Workbook(dataDir + "Book_Excel2007.xlsx", loadOptions2);
// Print message
System.out.println("Excel 2007 Workbook opened successfully.");

異なるフォーマットのファイルを開く

Aspose.Cellsを使用すると、SpreadsheetML、CSV、タブ区切りファイルなど、さまざまなフォーマットのスプレッドシートファイルを開くことができます。このようなファイルを開くには、Microsoft Excelの異なるバージョンのファイルを開くときと同じ手法を使用できます。

SpreadsheetML ファイルを開く

SpreadsheetMLファイルは、スプレッドシートのすべての情報(書式設定、数式など)を含むスプレッドシートのXML表現です。Microsoft Excel XP以降、Microsoft ExcelにXMLエクスポートオプションが追加され、スプレッドシートをSpreadsheetMLファイルにエクスポートできます。

SpreadsheetMLファイルを開くには、LoadOptionsクラスを使用してLoadFormat列挙型のSPREADSHEET_ML値を選択します。

// 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(OpeningSpreadsheetMLFiles.class) + "loading_saving/";
// Opening SpreadsheetML Files
// Creating and EXCEL_2003_XML LoadOptions object
LoadOptions loadOptions3 = new LoadOptions(LoadFormat.SPREADSHEET_ML);
// Creating an Workbook object with SpreadsheetML file path and the
// loadOptions object
Workbook workbook5 = new Workbook(dataDir + "Book3.xml", loadOptions3);
// Print message
System.out.println("SpreadSheetML format workbook has been opened successfully.");

CSV ファイルを開く

コンマ区切り値(CSV)ファイルには、値がコンマで区切られ、二重引用符で引用されたレコードが含まれています。 CSVファイルでは、データはコンマ文字で区切られ、二重引用符によって引用されたフィールドで保管されています。フィールドの値に二重引用符文字が含まれている場合は、一対の二重引用符文字でエスケープされます。また、Microsoft Excelを使用して、スプレッドシートのデータをCSVファイルにエクスポートすることもできます。

CSVファイルを開くには、LoadOptionsクラスを使用して、LoadFormat 列挙体で定義されたCSV値を選択してください。

// 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(OpeningCSVFiles.class) + "loading_saving/";
// Opening CSV Files
// Creating and CSV LoadOptions object
LoadOptions loadOptions4 = new LoadOptions(LoadFormat.CSV);
// Creating an Workbook object with CSV file path and the loadOptions
// object
Workbook workbook6 = new Workbook(dataDir + "Book_CSV.csv", loadOptions4);
// Print message
System.out.println("CSV format workbook has been opened successfully.");

CSV ファイルを開くと無効な文字を置換する

ExcelでCSVファイルを開くと、特殊文字が自動的に置き換えられます。Aspose.CellsのAPIも同様に、以下のコード例に示されているように自動的に置き換えます。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
//Source directory
String dataDir = Utils.getSharedDataDir(OpeningCSVFilesAndReplacingInvalidCharacters.class) + "LoadingSavingConvertingAndManaging/";
LoadOptions loadOptions = new LoadOptions(LoadFormat.CSV);
//Load CSV file
Workbook workbook = new Workbook(dataDir + "[20180220142533][ASPOSE_CELLS_TEST].csv", loadOptions);
System.out.println(workbook.getWorksheets().get(0).getName()); // (20180220142533)(ASPOSE_CELLS_T
System.out.println(workbook.getWorksheets().get(0).getName().length()); // 31
System.out.println("CSV file opened successfully!");

優先されるパーサを使用してCSVファイルを開く

CSVファイルを開く際にはデフォルトのパーサ設定を使用する必要はありません。時々、CSVファイルのインポートが期待通りの出力を作成しないことがあります。たとえば、日付形式が期待通りでない、または空のフィールドが異なる方法で扱われるなどです。そのために、要件に応じて異なるデータ型を解析するための優先されるパーサを提供するためにTxtLoadOptions.PreferredParsersが利用できます。以下のサンプルコードは、優先されるパーサの使用方法を示しています。  

この機能をテストするために、サンプルのソースファイルと出力ファイルを以下のリンクからダウンロードできます。

samplePreferredParser.csv

outputsamplePreferredParser.xlsx

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
class TextParser implements ICustomParser
{
@Override
public Object parseObject(String s) {
return s;
}
@Override
public String getFormat() {
return "";
}
}
class DateParser implements ICustomParser {
@Override
public Object parseObject(String s) {
Date myDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
try {
myDate = formatter.parse(s);
} catch (ParseException e) {
e.printStackTrace();
}
return myDate;
}
@Override
public String getFormat() {
return "dd/MM/yyyy";
}
}
public class OpeningCSVFilesWithPreferredParser {
//Source directory
private static String sourceDir = Utils.Get_SourceDirectory();
private static String outputDir = Utils.Get_OutputDirectory();
public static void main(String[] args) throws Exception {
// Initialize Text File's Load options
TxtLoadOptions oTxtLoadOptions = new TxtLoadOptions(LoadFormat.CSV);
// Specify the separatot character
oTxtLoadOptions.setSeparator(',');
// Specify the encoding scheme
oTxtLoadOptions.setEncoding(Encoding.getUTF8());
// Set the flag to true for converting datetime data
oTxtLoadOptions.setConvertDateTimeData(true);
// Set the preferred parsers
oTxtLoadOptions.setPreferredParsers(new ICustomParser[] { new TextParser(), new DateParser() });
// Initialize the workbook object by passing CSV file and text load options
Workbook oExcelWorkBook = new Workbook(sourceDir + "samplePreferredParser.csv", oTxtLoadOptions);
// Get the first cell
Cell oCell = oExcelWorkBook.getWorksheets().get(0).getCells().get("A1");
// Display type of value
System.out.println("A1: " + getCellType(oCell.getType()) + " - " + oCell.getDisplayStringValue());
// Get the second cell
oCell = oExcelWorkBook.getWorksheets().get(0).getCells().get("B1");
// Display type of value
System.out.println("B1: " + getCellType(oCell.getType()) + " - " + oCell.getDisplayStringValue());
// Save the workbook to disc
oExcelWorkBook.save(outputDir + "outputsamplePreferredParser.xlsx");
System.out.println("OpeningCSVFilesWithPreferredParser executed successfully.\r\n");
}
private static String getCellType(int type){
if(type == CellValueType.IS_STRING){
return "String";
} else if(type == CellValueType.IS_NUMERIC){
return "Numeric";
} else if(type == CellValueType.IS_BOOL){
return "Bool";
} else if(type == CellValueType.IS_DATE_TIME){
return "Date";
} else if(type == CellValueType.IS_NULL){
return "Null";
} else if(type == CellValueType.IS_ERROR){
return "Error";
} else{
return "Unknown";
}
}

TSV(タブ区切り)ファイルを開く

タブ区切りファイルには、書式はありませんが、表やスプレッドシートのような行と列でデータが配置されています。要するに、タブ区切りファイルは、各列の間にタブがある通常のテキストファイルの特別な種類です。

タブ区切りファイルを開くには、開発者はLoadOptionsクラスを使用し、TSV値を選択し、LoadFormat列挙型で事前定義する必要があります。

// 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(OpeningTabDelimitedFiles.class) + "loading_saving/";
// Creating and TAB_DELIMITED LoadOptions object
LoadOptions loadOptions5 = new LoadOptions(LoadFormat.TSV);
// Creating an Workbook object with Tab Delimited text file path and the
// loadOptions object
Workbook workbook7 = new Workbook(dataDir + "Book1TabDelimited.txt", loadOptions5);
// Print message
System.out.println("Tab Delimited workbook has been opened successfully.");

暗号化されたExcelファイルを開く

Microsoft Excelを使用して暗号化されたExcelファイルを作成することが可能であることはわかっています。このような暗号化されたファイルを開くためには、開発者は特別なオーバーロードされたLoadOptionsメソッドを呼び出し、FileFormatType列挙型で定義されたDEFAULT値を選択する必要があります。このメソッドは、以下の例に示すように、暗号化されたファイルのパスワードも受け取ります。

// 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(OpeningEncryptedExcelFiles.class) + "loading_saving/";
// Opening Encrypted Excel Files
// Creating and EXCEL_97_TO_2003 LoadOptions object
LoadOptions loadOptions6 = new LoadOptions(LoadFormat.EXCEL_97_TO_2003);
// Setting the password for the encrypted Excel file
loadOptions6.setPassword("1234");
// Creating an Workbook object with file path and the loadOptions object
Workbook workbook8 = new Workbook(dataDir + "encryptedBook.xls", loadOptions6);
// Print message
System.out.println("Encrypted workbook has been opened successfully.");

Aspose.Cellsはまた、パスワードで保護されたMS Excel 2013ファイルを開くのをサポートしています。

SXCファイルを開く

StarOffice CalcはMicrosoft Excelに似ており、数式、グラフ、関数、およびマクロをサポートしています。このソフトウェアで作成されたスプレッドシートはSXC拡張子で保存されます。SXCファイルはOpenOffice.org Calcスプレッドシートファイルにも使用されます。Aspose.Cellsは、以下のコードサンプルで示されるように、SXCファイルを読み取ることができます。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the source directory.
String sourceDir = Utils.Get_SourceDirectory();
// Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions = new LoadOptions(LoadFormat.SXC);
// Create a Workbook object and opening the file from its path
Workbook workbook = new Workbook(sourceDir + "SampleSXC.sxc", loadOptions);
// Using the Sheet 1 in Workbook
Worksheet worksheet = workbook.getWorksheets().get(0);
// Accessing a cell using its name
Cell cell = worksheet.getCells().get("C3");
System.out.println("Cell Name: " + cell.getName() + " Value: " + cell.getStringValue());

FODSファイルを開く

FODSファイルは、圧縮なしのOpenDocument XML形式で保存されたスプレッドシートです。Aspose.Cellsは、以下のコード例に示すように、FODSファイルを読み取ることができます。

// For complete examples and data files, please go to https://github.com/aspose-cells/Aspose.Cells-for-Java
// The path to the source directory.
String sourceDir = Utils.Get_SourceDirectory();
// Instantiate LoadOptions specified by the LoadFormat.
LoadOptions loadOptions = new LoadOptions(LoadFormat.FODS);
// Create a Workbook object and opening the file from its path
Workbook workbook = new Workbook(sourceDir + "SampleFods.fods", loadOptions);
// Print message
System.out.println("FODS file opened successfully!");

高度なトピック