--- lang: ja-jp breaks: true --- # C# NPOI を使用した、Excelシート内容の読み取り 2021-04-15 ## 環境 * Windows Server 2019 * Visual Studio 2017 * .Net Framework 4.5.2 * NPOI 2.3.0.0 ## 全てのセルの値を文字列として取得するサンプル ```csharp= /// <summary> /// /// </summary> /// <param name="xlsFile"></param> /// <param name="intMaxRowNumber"></param> /// <returns></returns> private List<string[]> GetXlsData( FileInfo xlsFile, int? intMaxRowNumber = null ) { List<List<ICell>> lstRows = new List<List<ICell>>(); using (FileStream stream = xlsFile.OpenRead()) { HSSFWorkbook hssfworkbook = new HSSFWorkbook(stream); try { ISheet sheet = hssfworkbook.GetSheetAt(0); int intLastRowNumber = sheet.LastRowNum; if ( intMaxRowNumber != null && intLastRowNumber > intMaxRowNumber ) { intLastRowNumber = intMaxRowNumber.Value; } for (int i = 0; i < intLastRowNumber; i++) { IRow row = sheet.GetRow(i); List<ICell> cells = new List<ICell>(); if (row != null) { foreach (ICell cell in row) { while (cells.Count < cell.ColumnIndex) { cells.Add(null as ICell); } cells.Insert(cell.ColumnIndex, cell); } } lstRows.Add(cells); } //IEnumerator rows = sheet.GetRowEnumerator(); //while (rows.MoveNext()) //{ // IRow row = rows.Current as HSSFRow; // List<ICell> cells = row.ToList(); // lstRows.Add(cells); //} } finally { hssfworkbook.Close(); } } int intMaxCol = lstRows.Max(n => n.Count); List<string[]> xlsData = new List<string[]>(); foreach (List<ICell> row in lstRows) { string[] strings = new string[intMaxCol]; int idxCol = 0; foreach (ICell cell in row) { if (cell != null) { //strings[idxCol] = cell.StringCellValue; strings[idxCol] = cell.ToString(); } idxCol++; } xlsData.Add(strings); } return xlsData; } ``` ###### tags: `NPOI` `C#` `Excel2003`
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up