You are viewing limited content. For full access, please sign in.

Question

Question

Exporting file to local computer to convert format and reimport

asked on July 19, 2016

I'm trying to compose a script to take a Laserfiche .csv file through ExportElecDoc so I can save it as an Excel file for further manipulation before importing it back in during the course of a workflow.  The script is working fine if I run it inside the SDK editor, but cannot find the file on my machine when I run it in the workflow.  I put messages in to track it and it is during the ExportElecDoc phase where it looks like it can't find the path.  I can't see why it works in the editor but not in the workflow, the script is the only activity in the workflow at the moment.  I haven't used the ExportElecDoc function before, but it looks like the parameters match what I've seen in the forums.  Anyone see where I'm going wrong here?  Here is the script, the view in the SDK error log showing the messages that the run succeeded, and the error log in the workflow showing where it didn't:

 

namespace WorkflowActivity.Scripting.SDKScript
{
    using System;
    using System.Collections.Generic;
    using System.Collections;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    using System.Text;
    using Laserfiche.RepositoryAccess;
    using Laserfiche.DocumentServices;
    using System.Linq;
    using System.Windows.Forms;
    using System.Security.Principal;
    using System.IO;
    using LFSO83Lib;
    using Laserfiche.RepositoryAccess.Data;
    using Laserfiche.RepositoryAccess.Common;
    using Microsoft.Office.Interop.Excel;
    //using SpreadsheetLight;
    using Excel = Microsoft.Office.Interop.Excel;


    public class Script1 : RAScriptClass91
    {
          protected override void Execute() {
            Session mySess = this.RASession;
            string myFile = "C:\\Users\\rick.nagy\\Desktop\\Exportedcsv.csv";
            this.WorkflowApi.TrackInformation("Logged in to repo");

            DocumentInfo di = Document.GetDocumentInfo(2789782, mySess);
            if (di.IsElectronicDocument){
                this.WorkflowApi.TrackInformation("checking extension");
                MsgBox(" Document Extension: " + di.Extension);
                }

            DocumentExporter de = new DocumentExporter();
            de.ExportElecDoc(di, myFile);
            di.Dispose();
            this.WorkflowApi.TrackInformation("Exporting document");

            StreamReader objReader = new StreamReader(myFile);
            string sLine = "";
            ArrayList arrText = new ArrayList();
            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                    arrText.Add(sLine);
            }

            callExcel(arrText, true);

            DocumentInfo docInfo = new DocumentInfo(mySess);
            DocumentImporter dic = new DocumentImporter();
            dic.Document = docInfo;
            string path = "\\NorthStar\\MIS\\RicksGeminiTest\\TempHold\\HeyJag\\";
            docInfo.Create(Folder.GetFolderInfo(path, mySess), "Your Excel Report", "DEFAULT", EntryNameOption.AutoRename);
            docInfo.Unlock();
            dic.ImportEdoc("application/application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", myFile);
            docInfo.Dispose();
            this.WorkflowApi.TrackInformation("Report was saved");
        }
         private void callExcel(ArrayList arrText, bool value)
        {
            try
            {
            String textString = null;
            foreach (var item in arrText)
            {
            textString = textString + item + Environment.NewLine;
            }
        Clipboard.SetText(textString);
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        //xlexcel.Visible = true;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.Paste(CR, false);
        if (value == true) {
            try {
                // saving the file as .xls
                xlWorkSheet.SaveAs(@"C:\Users\rick.nagy\Desktop\receivedNew.xls");
                }
            catch (Exception){
                MessageBox.Show("File already exists");
                }
                }
             else {
                try {
                // saving the file as .xlsx
                xlWorkSheet.SaveAs(@"C:\Users\rick.nagy\Desktop\receivedNew.xlsx");
                }
                catch (Exception){
                MessageBox.Show("File already exists");
                }
                }
             xlexcel.Quit();
             }
                catch(Exception ex){
                MessageBox.Show(ex.ToString());
                }
                }
    }
}

 

0 0

Answer

SELECTED ANSWER
replied on July 19, 2016

You have to keep in mind the context in which your program is running. When you run the SDK Script from Workflow Designer on your local computer, you are running it locally as your Windows account. When Workflow is running it, it is running it on the Workflow server as whatever login you have configured the WF Server Service to run as. Are your file paths written in a way that makes sense if referenced from the WF server? If yes, does the WF Service Account have rights to those folders?

1 0

Replies

replied on July 19, 2016

0 0
replied on July 19, 2016

Thanks, Scott.  You were right, I put the file on the workflow server instead and it works just fine.  Then I found out why you shouldn't use Interop.Excel on a server, man what a headache.  Mismatched versions of Excel, mismatched .dll files.  I've tried like four different programs, what I finally got working was EPPlus, which works even without the server having Office at all.  This will actually work out nice, the user can submit date ranges in a Laserfiche form, it dumps into the repository and starts a workflow to search through and gather the data, and they end up with a report in Forms, and also an Excel file at the end as well.  It was initially a .csv populated through a script, but this EPPlus integration lets me size the columns and bold the rows so it comes out really clean looking and nice!  Appreciate your help!

0 0
replied on August 25, 2017

Hi Rick,

Do you have a sample code using EPPlus that you can share with me? I need to dump a SQL select from workflow into a an excel file and this solution looks like the way to go.

0 0
replied on August 28, 2017

Hi Pedro,

Sure thing.  I have a workflow kick off and write a .csv file from tokens in the workflow I gathered, and then I use a script with the EPPlus program to write it to an XLS or XLSX and format it the way I want.  I just used an instance of StreamWriter to write the CSV but if you want a copy of that I will post it as well.  Here is the code to use EPPlus to take the .csv and write it nicely to XLSX format:

namespace WorkflowActivity.Scripting.SDKScript2
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Data.SqlClient;
    using System.Text;
    using Laserfiche.RepositoryAccess;
    using Laserfiche.DocumentServices;
    using System.Collections;
    using System.Linq;
    using System.IO;
    using OfficeOpenXml;
    using OfficeOpenXml.Drawing;
    using OfficeOpenXml.Style;
    using System.Drawing;
    using OfficeOpenXml.ConditionalFormatting;

    public class Script1 : RAScriptClass91
    {
      protected override void Execute()
        {
        Session mySess = this.RASession;
        string ent = this.TokenReplace("%(FindEntry_OutputEntry_ID)");
        int entID = int.Parse(ent);
        DocumentInfo docInfo = Document.GetDocumentInfo(entID, mySess);
        StreamReader objReader = new StreamReader("C:\\Users\\svc_laserfiche\\My Documents\\Qualified Plans CSV\\ReportTester.csv");
        string sLine = "";
        ArrayList arrText = new ArrayList();
        while (sLine != null)
          {
             sLine = objReader.ReadLine();
             if (sLine != null)
              arrText.Add(sLine);
          }
        string csvFileName = "C:\\Users\\svc_laserfiche\\My Documents\\Qualified Plans CSV\\ReportTester.csv";
        string excelFileName = "C:\\ProgramData\\Laserfiche\\WF\\ServerData\\$\\0000\\0000\\0000\\TempReportFiles\\007F.1.xlsx";
        string worksheetsName = "Worksheet1";
        bool firstRowIsHeader = true;
        var format = new ExcelTextFormat();
        format.Delimiter = ',';
        format.EOL = "\r";
        using (ExcelPackage package = new ExcelPackage(new FileInfo(excelFileName))) {
            package.Workbook.Worksheets.Delete("Worksheet1");
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);
            worksheet.Cells["A2"].LoadFromText(new FileInfo(csvFileName), format, OfficeOpenXml.Table.TableStyles.Medium27, firstRowIsHeader);
            int totalRows = worksheet.Dimension.End.Row;
            int totalCols = worksheet.Dimension.End.Column;
            var headerCells = worksheet.Cells[1,1,1,totalCols];
            var headerFont = headerCells.Style.Font;
            headerFont.Bold = true;
            
                 using (ExcelRange rng = worksheet.Cells["A2:I2"])
                {
                    rng.Style.Font.Bold = true;
                    rng.Style.Fill.PatternType = ExcelFillStyle.Solid;            //Set Pattern for the background to Solid
                    rng.Style.Fill.BackgroundColor.SetColor(Color.DarkBlue);  //Set color to dark blue
                    rng.Style.Font.Color.SetColor(Color.White);
                 }
            worksheet.Cells[1, 1].Value = "New Hire Status Report";
            worksheet.Cells[1, 1, 1, 9].Merge = true;
            worksheet.Cells[1, 1, 1, 9].Style.Font.Bold = true;
            worksheet.Cells[1, 1, 1, 9].Style.Font.Size = 22;
            worksheet.Cells[1, 1, 1, 9].Style.Font.Color.SetColor(Color.DarkBlue);
            worksheet.Row(1).Height = 35;
            worksheet.Cells[1, 1, 1, 9].Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            worksheet.Cells[3, 1, totalRows, 9].Style.HorizontalAlignment = ExcelHorizontalAlignment.Left;
            worksheet.Column(2).Style.Numberformat.Format = @"MM/dd/yyyy";
            worksheet.Column(4).Style.Numberformat.Format = @"MM/dd/yyyy";
            worksheet.Column(8).Style.Numberformat.Format = @"MM/dd/yyyy";
            worksheet.Column(9).Style.Numberformat.Format = @"";
            worksheet.Column(7).AutoFit();
            worksheet.Column(2).AutoFit();
            worksheet.Column(1).AutoFit();
            worksheet.Column(8).AutoFit();
            worksheet.Column(6).AutoFit();
            worksheet.Column(3).Width = 28;
            worksheet.Column(3).Style.WrapText = true;
            worksheet.Column(4).Width = 53;
            worksheet.Column(4).Style.WrapText = true;
            worksheet.Column(5).Width = 39;
            worksheet.Column(5).Style.WrapText = true;
            worksheet.Column(9).Width = 10;
            worksheet.Column(9).Style.WrapText = true;
            worksheet.TabColor = Color.Black;
            worksheet.View.FreezePanes(3,10);
            package.Save();
        }
      }
    }
 }

As you will see, it is much easier than using InteropExcel.  You can download it free here:  http://epplus.codeplex.com/

You will want version 4.1.  After that, just reference the EPPLus dll in your script, and then also put in using statements at the top for OfficeOpenXml, OfficeOpenXml.Drawing, and OfficeOpenXml.Style.  Let me know if you would like anything else, glad to help!

 

Rick

0 0
replied on August 29, 2017

Thanks Rick, I will test it and let you know.

Thanks again.

0 0
replied on January 25, 2019

Hi what references did you include especially when you want to focus on the csv files format only?

0 0
replied on January 25, 2019

Hi Prudence,

I just added System.IO and System.Text in order to use StreamWriter and StringBuilder classes.  

1 0
replied on January 27, 2019 Show version history

Hi Rick 

 

 using Excel = Microsoft.Office.Interop.Excel;

I am not able to use that is there a specific reference that i should add to the script, mainly focus on the .csv extension not .xls ? 

 

replied on April 21, 2021

Rick - Thanks for your post.

Out of curiosity, why couldn't you create the excel format directly instead of creating the csv file first?  I am trying to create the excel file also, wondering if this is a requirement to creating excel or just a design thing...thanks

0 0
replied on April 21, 2021 Show version history

To create an Excel file in Workflow takes a bit of scripting.

The way I would handle this is have a blank Excel doc in the Repository or on the local drive.  Then have workflow copy and rename the file to a specific location on the drive where an ODBC System DSN is pointed at an Excel file.  Then you can use a standard Insert Data activity to write directly to the Excel.

0 0
replied on April 21, 2021

Bert - I am not familiar with Workflow as much as I am with script.  What is the activity to copy from repo to disk?   Seems like the create entry or move entry destination are for the repo.

1 0
replied on April 27, 2021

There is not any built in activity to export/import to Windows file system and this must be scripted.

0 0
You are not allowed to follow up in this post.

Sign in to reply to this post.