发布:2023/3/24 22:31:26作者:管理员 来源:本站 浏览次数:707
一、引用NuGetGet里的npoi,如下图:
二、打开文件
Stream stream = File.OpenRead(@"C:\Test\\11.docx");
XWPFDocument doc = new XWPFDocument(stream);
三、获取word里面所有的表格
var allTables = doc.Tables;
四、获得表格的所有行
var rows = table.Rows;
五、获得行下的所有列
var cells = row.GetTableCells();
六、获得列里的图片
var run = cell.Paragraphs[0].Runs[0];
List<XWPFPicture> xwpfPictureList = run.GetEmbeddedPictures();
七、得到图片的二进制数据
var data = xwpfPictureList[0].GetPictureData();
var picData = data.Data;
八、把二进制转换为image并保存到本地
var image = GetImageFromByte(picData);
image.Save(@"C:\Test\pics\\0603-" + i + ".png");
下面是完整的代码:
Stream stream = File.OpenRead(@"C:\Test\\11.docx");
XWPFDocument doc = new XWPFDocument(stream);
var allTables = doc.Tables;
int i = 1;
foreach (var table in allTables)
{
var rows = table.Rows;
foreach (var row in rows)
{
var cells = row.GetTableCells();
foreach (var cell in cells)
{
if (cell.Paragraphs[0].Runs.Count > 0)
{
var run = cell.Paragraphs[0].Runs[0];
List<XWPFPicture> xwpfPictureList = run.GetEmbeddedPictures();
if (xwpfPictureList.Count > 0)
{
var data = xwpfPictureList[0].GetPictureData();
var picData = data.Data;
var image = GetImageFromByte(picData);
image.Save(@"C:\Test\pics\\0603-" + i + ".png");
i++;
}
}
}
}
}
public System.Drawing.Image GetImageFromByte(byte[] streamByte)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(streamByte);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
return img;
}
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4