@manhng

Welcome to my blog!

Read Excel File using Open XML

June 6, 2021 22:04

Read Excel File using Open XML (edit)

Read Excel File (.xlsx)

using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;

namespace DocumentFormatOpenXmlConsoleApp
{
/// <summary>
/// https://stackoverflow.com/questions/7504285/how-to-retrieve-tab-names-from-excel-sheet-using-openxml
/// https://stackoverflow.com/questions/23102010/open-xml-reading-from-excel-file
/// https://gist.github.com/manhng83/e2dd3fc1e33c4af22801667d3f2f3c5a (ReadWriteExcel.cs)
/// </summary>
internal class Program
{
private static void Main(string[] args)
{
string fileName = @"C:\20210604.xlsx";
StringBuilder sb = new StringBuilder();

// Open the document for editing.
using (SpreadsheetDocument spreadsheetDocument =
SpreadsheetDocument.Open(fileName, false))
{
WorkbookPart workbookPart = spreadsheetDocument.WorkbookPart;

int sheetIndex = 0;
string str = string.Empty;

SharedStringTablePart sstpart = workbookPart.GetPartsOfType<SharedStringTablePart>().First();
SharedStringTable sst = sstpart.SharedStringTable;


foreach (WorksheetPart worksheetpart in workbookPart.WorksheetParts)
{
try
{
Worksheet worksheet = worksheetpart.Worksheet;

string sheetName = workbookPart.Workbook.Descendants<Sheet>().ElementAt(sheetIndex++).Name;

//Work with only dtb_*** & mtb_***
if (!(sheetName.StartsWith("dtb_") || sheetName.StartsWith("mtb_"))) continue;

Console.WriteLine(sheetName);
sb.AppendLine(sheetName);
sb.AppendLine("----------------------------------------------------------------------------------------------------");

foreach (SheetData sheetData in worksheet.Elements<SheetData>())
{
try
{
var cells = sheetData.Descendants<Cell>();
var rows = sheetData.Descendants<Row>();

Console.WriteLine("Row count = {0}", rows.LongCount());
Console.WriteLine("Cell count = {0}", cells.LongCount());

bool found = false;

foreach (Cell cell in cells)
{
if ((cell.DataType != null) && (cell.DataType == CellValues.SharedString))
{
int ssid = int.Parse(cell.CellValue.Text);
str = sst.ChildElements[ssid].InnerText;

if (str == "Tên logic")
{
found = true;
continue;
}
if (found)
{
sb.AppendFormat("\r\nShared string {0}: {1}", ssid, str);
}
}
else if (cell.CellValue != null)
{
str = cell.CellValue.Text;
if (str == "Tên logic")
{
found = true;
continue;
}
if (found)
{
//Console.WriteLine("Cell contents: {0}", str);
}
}
}
//sb.AppendLine();
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
throw;
}
}
Console.WriteLine("----------");
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
throw;
}
}
}
Console.WriteLine(sb.ToString());
File.WriteAllText("Output.txt", sb.ToString(), Encoding.UTF8);
Process.Start(@"C:\Program Files\Notepad++\notepad++.exe", "Output.txt");
Console.ReadLine();
}
}
}

Categories

Recent posts