使用EPplus将文本添加到Excel

我有一个主目录,其中包含许多子目录。 在每个子目录中都会有图像。 我设法将每个子目录中的图像导出到Excel工作簿中的每个Excel电子表格中。 例如,如果我有10个子目录,将会有1个excel工作簿和10个excel电子表格,每个电子表格中会有每个子目录的图像。

我现在要完成的是如果在任何子目录中没有图像,导出到Excel电子表格的子目录将是空白的。 我想添加“找不到图像”作为文本的空白Excel电子表格。

这是我曾经试过的:

foreach (string subdir in filesindirectory) { string[] splitter = subdir.Split('\\'); string folderName = splitter[splitter.Length - 1]; ExcelWorksheet ws = package.Workbook.Worksheets.Add("Worksheet-" + folderName); //create new worksheet ImageCount = 0; if (Directory.GetFiles(subdir).Length == 0) { ws.Cells["J9:L10"].Merge = true; ws.Cells["J9:L10"].Style.VerticalAlignment = ExcelVerticalAlignment.Top; ws.Cells["J9:L10"].Value = "No chart to display"; ws.Cells["J9:L10"].Style.Font.Size = 16; } foreach (string img in Directory.GetFiles(subdir)) { ImageCount++; System.Drawing.Image Image1 = System.Drawing.Image.FromFile(img); var AddImage = ws.Drawings.AddPicture("Image" + ImageCount.ToString(), Image1 ); Image1 .Dispose(); // Row, RowoffsetPixel, Column, ColumnOffSetPixel if (ImageCount > 1) { AddImage .SetPosition(ImageFinalPosition, 0, 2, 0); AddImage .SetSize(770, 450); ImageFinalPosition += (ImagePosition + 1); // Add 1 to have 1 row of empty row } else { AddImage.SetPosition(ImageCount, 0, 2, 0); AddImage.SetSize(770, 450); ImageFinalPosition = (ImageCount + ImagePosition) + 1; // Add 1 to have 1 row of empty row } 

我现在面对的问题是,当我将文本添加到特定的合并单元格时,如果我查看具有不同屏幕尺寸的电子表格,较小的屏幕尺寸将在电子表格中心显示文本,而较大的屏幕尺寸将显示电子表格左侧的文本。

这是我看到的一个样本:

较小的屏幕尺寸(笔记本电脑): 在这里输入图像说明 更大的屏幕尺寸(桌面): 在这里输入图像说明 这是我想要达到的输出(所有屏幕大小): 在这里输入图像说明 请帮助我,谢谢!

你必须了解foreach循环是如何工作的
如果你的count0你的foreach代码根本不运行
你应该在foreach循环之前把你的检查写在工作表里面

按照以下方式将您的代码放在foreach循环之前

 if (Directory.GetFiles(subdir).Length == 0) //if no image in that sub directory { ws.Cells["A1:A3"].Merge = true; ws.Cells["A1:A3"].Style.VerticalAlignment = ExcelVerticalAlignment.Top; ws.Cells["A1:A3"].Style.Border.Top.Style = ExcelBorderStyle.Thin; ws.Cells["A1:A3"].Style.Border.Left.Style = ExcelBorderStyle.Thin; ws.Cells["A1:A3"].Style.Border.Right.Style = ExcelBorderStyle.Thin; ws.Cells["A1:A3"].Style.Border.Bottom.Style = ExcelBorderStyle.Thin; ws.Cells["A1:A3"].Style.Fill.PatternType = ExcelFillStyle.Solid; ws.Cells["A1:A3"].Style.Fill.BackgroundColor.SetColor(System.Drawing.ColorTranslator.FromHtml("#f0f3f5")); ws.Cells["A1:A3"].Value = "content not found"; } foreach (string img in Directory.GetFiles(subdir)) { // Your else code }