【发布时间】:2016-01-22 15:13:50
【问题描述】:
我有一个目录“文件夹”,其中包含许多子目录。在每个子目录中都有许多图像。我想遍历“文件夹”目录中的子目录,然后遍历每个目录中的所有图像以将图像导出到 Excel,并将每个子目录中的图像放在一个 Excel 工作表中。
例如如果我有十个子目录,我应该有一个 Excel 工作簿和十个 Excel 工作表,然后在每个 Excel 工作表中都会有来自每个子目录的图像。
这是我尝试过的,但图像只出现在 Worksheet1 而不是所有工作表上:
public void ExportToExcel()
{
//for export
ExcelPackage objExcelPackage = new ExcelPackage(); //create new workbook
string[] filesindirectory = Directory.GetDirectories(Server.MapPath("~/Folder"));
int count = 0;
int count1 = 0;
int x = 25;
int finalValue = 0;
foreach (string subdir in filesindirectory)
{
count++;
ExcelWorksheet ws = objExcelPackage.Workbook.Worksheets.Add("Worksheet" + count); //create new worksheet
foreach (string img in Directory.GetFiles(subdir))
{
count1++;
System.Web.UI.WebControls.Image TEST_IMAGE = new System.Web.UI.WebControls.Image();
System.Drawing.Image myImage = System.Drawing.Image.FromFile(img);
var pic = ws.Drawings.AddPicture(count1.ToString(), myImage);
// Row, RowoffsetPixel, Column, ColumnOffSetPixel
if (count1 > 1)
{
pic.SetPosition(finalValue, 0, 2, 0);
finalValue += (x + 1); // Add 1 to have 1 row of empty row
}
else
{
pic.SetPosition(count1, 0, 2, 0);
finalValue = (count1 + x) + 1; // Add 1 to have 1 row of empty
}
}
}
var filepath = new FileInfo(@"C:\Users\user\Desktop\Test\" + datetime.ToString("dd-MM-yyyy_hh-mm-ss") + ".xlsx");
objExcelPackage.SaveAs(filepath);
}
如何循环遍历一个目录下的每个子目录,然后用C#循环遍历每个子目录下的所有图片?
【问题讨论】:
-
你遇到了什么错误?
-
嗨@Micky,我在这一行收到错误:'foreach(subdir 中的字符串 img)',错误是“无法将 char 转换为字符串”。
-
这可能会给你一些想法:stackoverflow.com/questions/29991439/…
-
您可能想要考虑在您的 Web 应用程序与之通信的单独服务中执行此类操作。 Web 应用在底层 OS 系统中的范围应该是有限的。
-
@CallumLinington 这取决于。有些人喜欢折叠层。
标签: c# asp.net excel directory subdirectory