我有一个想要用作发票的格式化Excel工作表。我希望能够遍历特定文件夹中的所有文件,并在特定单元格中添加文件名,并在下面插入新行。
我目前具有以下内容,但我找不到任何可以使我在非常特定的范围内添加新内容,然后继续在其下添加新内容,同时保持Excel文件格式的良好示例。
string path = @"C:\MyWorkingFolder";
string rootfolder = Path.GetDirectoryName(path);
string folder = Path.GetFileName(Path.GetDirectoryName(path));
var xlApp = new Microsoft.Office.Interop.Excel.Application();
var xlWorkBook = xlApp.Workbooks.Open(fileName, ReadOnly: true);
Worksheet xlWorkSheet = xlWorkBook.Sheets["Invoice"];
DirectoryInfo d = new DirectoryInfo(rootfolder);
int count = d.GetFiles("*.doc*").Length;
Console.WriteLine("Found {0} files.", count);
Console.Write("Press any key to continue.");
Console.ReadKey();
foreach (var file in Directory.EnumerateFiles(rootfolder, "*.doc*"))
{
Console.WriteLine("Processing...");
string FileName = Path.GetFileName(file);
WriteFileNameToExcel(xlWorkSheet, FileName);
}
Console.WriteLine("Done.");
Console.Write("Press any key to End.");
Console.ReadKey();
// Disable file override confirmaton message
xlApp.DisplayAlerts = false;
string newfile = string.Format(rootfolder + @"\" + "H&K Invoice - {0}.xlsx", DateTime.Now.ToString("dd_MM_yyyy"));
xlWorkBook.SaveAs(newfile, Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);
xlWorkBook.Close();
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
private static void WriteFileNameToExcel(Worksheet ws, string filename)
{
//How to target the specific cell, then insert new rows so as to maintain formatting
}
答案 0 :(得分:0)
插入行,保持上面的格式:
Rows("8:8").Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
在不更改格式的情况下向该新行添加内容:
Cells(8,1).value = "This is new"
增加变量的趣味性以获取当前的最后一行,并在其下添加新行。