0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【C#】Aspose.cellsとOpenFileDialogを使ってみた

Posted at

C#で作成するツールにて、ダイアログを表示してExcelのパスを取得し、該当Excelを開いて内容を取得する必要がでたため、Aspose.cellsとOpenFileDialogで実装を行った。
以下に簡単にAspose.cellsとOpenFileDialogについてまとめます。

Aspose.cellsとは何か?

XLS を作成するための高速 C# ライブラリ。これは、XLSX、PDF、および .NET フレームワーク、.NET コアまたは Mono プラットフォーム上のその他の多くの形式をインポートおよびエクスポートするためのApiです。
⇒Excelの操作が簡単にできるようになるApiということ。

導入方法

dllとライセンスファイルをプログラムに置くだけでした。

使用例

ライセンス設定
// ライセンス設定(Aspose.Cells.licを「埋め込まれたリソース」に設定すること)
Aspose.Cells.License license = new Aspose.Cells.License();
license.SetLicense("Aspose.Cells.NET.lic");
ワークブックを取得する
//Create a workbook object
Workbook workbook = new Workbook(INPUTFILEPATH); ⇒INPUTFILEPATH:読み込みたいExcelのパス 
ワークシートを取得する。(1ページ目を取得)
//Get the first worksheet in the workbook
Worksheet worksheet = workbook.Worksheets[0];
セルの内容を取得
//Get the cells collection in the sheet
Cells cells = worksheet.Cells;
ワークシートから空白行/列を削除する。
 worksheet.Cells.DeleteBlankRows();
 worksheet.Cells.DeleteBlankColumns();
データテーブルにExcelから取得内容を格納
// Exporting the contents of 7 rows and 2 columns starting from 1st cell to DataTable
DataTable dataTable = worksheet.Cells.ExportDataTableAsString(int firstrow, int firstColumn, int totalrows, int totalColumns, bool exportColumnName);
例:各シート毎に空の判定を行う。
for (int i = 0; i<workbook.Worksheets.Count; i++)
{
    Worksheet worksheet = workbook.Worksheets[i];
    Cells cells = worksheet2.Cells;
    if (cells.Count > 0)
    {
         // 入力あるシートの処理
    }
    else
    {
        // 空シートの処理
    }
}

ダイアログを表示する方法

OpenFileDialog クラス

ユーザーにファイルを開けるように指示するダイアログ ボックスを表示します。 このクラスは継承できません。

var fileContent = string.Empty;
var filePath = string.Empty;

using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
    openFileDialog.InitialDirectory = "c:\\";
    openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    openFileDialog.FilterIndex = 2;
    openFileDialog.RestoreDirectory = true;

    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        //Get the path of specified file
        filePath = openFileDialog.FileName;

        //Read the contents of the file into a stream
        var fileStream = openFileDialog.OpenFile();

        using (StreamReader reader = new StreamReader(fileStream))
        {
            fileContent = reader.ReadToEnd();
        }
    }
}

MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?