Protect Excel worksheet in C #

2

In a C # application, it can take from 1 to 2100 hours of data gathering. The data is saved in a CSV Excel spreadsheet every minute. With the code below we can hide and show the file.

    #region
    string diret=saveFileDialog1.FileName;
    Encoding sjisX=Encoding.GetEncoding("Shift_JIS");
    StreamWriter arquivo=new StreamWriter(diret,true,sjisX);
    FileInfo fileProtec=new FileInfo(saveFileDialog1.FileName);
    fileProtec.Attributes=FileAttributes.Archive;
    arquivo.Write(tb_csv.Text);
    arquivo.Close();
    fileProtec.Attributes=FileAttributes.Hidden;
    #endregion

Even with this protection, you can open the file in Excel. If the file is open the data will not be saved. What is the smart and smart way to prevent this file from being opened until data collection is complete?

    
asked by anonymous 13.07.2017 / 11:09

1 answer

3

Use SpreadsheetLight .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Spreadsheet;
using SpreadsheetLight;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            SLDocument sl = new SLDocument();

            // Note that there's no password protection.
            // This just prevents the casual user from editing the
            // worksheet.

            SLSheetProtection sp = new SLSheetProtection();
            sp.AllowInsertRows = true;
            sp.AllowInsertColumns = false;
            sp.AllowFormatCells = true;
            sp.AllowDeleteColumns = true;
            sl.ProtectWorksheet(sp);

            // Use this to unprotect the currently selected worksheet.
            //sl.UnprotectWorksheet();

            // Note that this only unprotects worksheet without password protection.

            sl.SetCellValue(2, 2, "I'm protected. Sort of...");

            sl.SaveAs("WorksheetProtection.xlsx");

            Console.WriteLine("End of program");
            Console.ReadLine();
        }
    }
}
    
13.07.2017 / 13:18