1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

C#でClosedXMLを使ってExcelのシートを新規追加

Posted at

自分用メモ

指定したExcelファイルにシートを新規追加したい~
同じ名前のシートがあったら削除して新規追加します。

開発中は try catch なしでやらないとどこでエラーになったのかわからんので注意。

CreateNewSheet.cs
public void CreateNewSheet()
{
	string sheetName = "新規追加したいシート名";
	string excelFilePath = (Excelファイルがあるフルパス);

	try
	{
		var book = new XLWorkbook( excelFilePath );
		var sheet = book.Worksheet( 1 );

		//シート「新規追加したいシート名」が存在している
		if (book.TryGetWorksheet( sheetName, out sheet ) == true)
		{
			book.Worksheet( sheetName ).Delete();   //削除
		}

		//シート「新規追加したいシート名」を新規追加
		book.AddWorksheet( sheetName, 1 );

		//保存
		book.Save();
	}
	catch( Exception e )
	{
		string error = "";
		error += "使用するファイルが開かれています。\n";
		error += "選択したExcelファイルを閉じてください。。\n\n";

		string title = "入力ファイルの読み込みエラー";

		MessageBox.Show( error, title, MessageBoxButtons.OK, MessageBoxIcon.Error );

		throw e;
	}
}
1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?