Protect Excel spreadsheet in C#

Asked

Viewed 141 times

2

In a C#application, you can have from 1 to 2100 hours of data collection. 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 it is possible to open the file in Excel. If the file is open the data will not be saved. What a smart and smart way to prevent this file from opening until the data harvest is completed?

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();
        }
    }
}
  • Hi Thiago, I edited the question. It is possible to use Spreadsheetlight with csv?

  • Wow, in vdd your doubt has nothing to do with Excel. CSV is not spreadsheet, but only a text file. I recommend changing the extension to .DAT. Before starting import, make a copy of the file and read from the copy.

  • I will accept your answer due to the fact that before editing the question, the reference was Excel; then you answered. Very grateful.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.