1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Excelファイルの図形に記入されたテキストを読み取る

Posted at

xlsxファイルの実体はzipファイルで、展開すると、
展開先フォルダー\xl\drawings フォルダーに、シート毎に格納される。

NuGetでSharpZipLibを導入する必要があります。

テストする場合は、適当にExcelファイルを作って保存して、
変数 excelFilePath にそのファイル名を代入して下さい。

using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
using System.Xml;

namespace ConsoleApp1
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //展開したいExcelファイル名
            //例:C:\Users\Owner\Desktop\Book1.xlsx
            string excelFilePath = @"C:\Users\Unko\Desktop\Book1.xlsx";

            //Excelファイルの展開先フォルダー
            string extractedPath = Path.Combine(Path.GetDirectoryName(excelFilePath), "Temp");

            new FastZip().ExtractZip(excelFilePath, extractedPath, null);

            //図形データは下記のフォルダーに、シート単位で、XML形式で格納されている。
            string drawingDirectories = Path.Combine(extractedPath, "xl", "drawings");

            foreach (string drawing in Directory.GetFiles(drawingDirectories))
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(drawing);

                XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                nsmgr.AddNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
                nsmgr.AddNamespace("xdr", "http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing");


                XmlNodeList paragraphNodes = doc.SelectNodes("//a:p", nsmgr);
                int index = 1;
                foreach (XmlNode pNode in paragraphNodes)
                {
                    string paragraphText = "";

                    XmlNodeList tNodes = pNode.SelectNodes(".//a:t", nsmgr);
                    foreach (XmlNode tNode in tNodes)
                    {
                        paragraphText += tNode.InnerText;
                    }

                    Console.WriteLine(paragraphText);
                }
            }
        }
    }
}
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?