获取Excel工作簿的路径或文件名

时间:2017-03-13 06:46:26

标签: c# excel

如何在下面的代码中获取工作簿的路径或文件名,以便我可以获取已编辑的工作簿。我使用了ExpertXLS - 用于.NET的Excel电子表格库 - C#/ VB.NET

using ExpertXls;

namespace IQC
{
     public class CSFB
     {
          public static string GenerateTemplateForCurrentGridView(IQO[] items, string colname, int icol)
          {
              /*Some Code here*/
              string pathSource = HttpContext.Current.Server.MapPath("~/pdf/ExportTemplate.xlsx");
              ExpertXls.ExcelLib.ExcelWorkbook workbook = new ExpertXls.ExcelLib.ExcelWorkbook(@pathSource);
              workbook.LicenseKey = Inq.Configuration.Settings.Value("ExpertPdfLicenseKey");
              ExpertXls.ExcelLib.ExcelWorksheet ws = workbook.Worksheets["ImportTemplate"];
              ExpertXls.ExcelLib.ExcelCellStyle Style1 = workbook.Styles.AddStyle("Style1");
              Style1.Fill.FillType = ExpertXls.ExcelLib.ExcelCellFillType.SolidFill;
              Style1.Fill.SolidFillOptions.BackColor = Color.Yellow;
              foreach (string cols in colname.Split(','))
              {
                   ws[cols].Style = Style1;                       
              }
                /*Some Code here*/
           }
     }
}

2 个答案:

答案 0 :(得分:2)

如果工作簿是活动工作簿,则可以使用Application.ActiveWorkbook.FullName。您也可以尝试使用workbook.Path。请参阅link

答案 1 :(得分:1)

添加以下代码有效。我已将工作书保存在“pathsource”

System.IO.FileStream fs = new FileStream(pathSource, FileMode.OpenOrCreate, FileAccess.ReadWrite);
 string fileName = fs.Name;
 try
 {
     workbook.Save(fs);
 }
 catch (Exception ex)
 {                      
     Logger.Error(" Error:", ex);
 }
 finally
 {                       
     workbook.Close();
 }