Pagina .cs:
codice:
using ExcelDataReader;
using RegistroPrivacy.Helpers;
using RegistroPrivacy.Models;
using System;
using RegistroPrivacy.Repositories;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Web;
using System.Web.Mvc;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS.FileSystem;
using NPOI.SS.UserModel;
using System.Text;
using NPOI.SS.Util;
using System.Data.Entity.Core.EntityClient;
namespace RegistroPrivacy.Controllers
{
[UFRPUserAuthorize(Roles = "Admin")]
[UFRPUserPasswordCheckAttribute]
public class RPImportController : Controller
{
static public byte[] b;
string message = "";
private static readonly log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
readonly ISocietaRepository societaRepository;
readonly IRPImportHelper importHelper;
public RPImportController(IRPImportHelper importHelper, ISocietaRepository societaRepository)
{
this.importHelper = importHelper;
this.societaRepository = societaRepository;
}
// GET: RPImport
public ActionResult ImportData()
{
return View();
}
// POST: RPImport
[HttpPost]
[ValidateAntiForgeryToken]
[LogFilter]
public ActionResult ImportData(HttpPostedFileBase uploadfile)
{
if (ModelState.IsValid)
{
if (uploadfile != null && uploadfile.ContentLength > 0)
{
IExcelDataReader reader = null;
Stream stream = uploadfile.InputStream;
DataSet result = null;
try
{
reader = ExcelReaderFactory.CreateReader(stream);
result = reader.AsDataSet();
} catch (Exception e)
{
log.Fatal(e);
ModelState.AddModelError("uploadfile", SocietaModelMessages.SocietaModelMessages.invalidFormat);
return View();
} finally
{
if (reader!=null)
{
reader.Close();
}
}
DataTable dataTable = result.Tables[0];
var validationErrors = importHelper.validate(dataTable, User);
if (validationErrors.Count == 0)
{
List<RPTrattamento> tuttiTrattamenti = importHelper.tranformData(dataTable, User);
var trattamentiPerSocieta = new Dictionary<int, List<RPTrattamento>>();
foreach (var trattamento in tuttiTrattamenti)
{
if (!trattamentiPerSocieta.ContainsKey(trattamento.SocietaId))
{
var listSocieta = new List<RPTrattamento>();
listSocieta.Add(trattamento);
trattamentiPerSocieta.Add(trattamento.SocietaId, listSocieta);
} else
{
var listSocieta = trattamentiPerSocieta[trattamento.SocietaId];
listSocieta.Add(trattamento);
}
}
var message = new List<string>();
foreach (var item in trattamentiPerSocieta)
{
int societaId = item.Key;
var db = new SocietaModelContainer(societaRepository.GetSocietaContext(societaId));
db.RPTrattamentoSet.AddRange(item.Value);
db.SaveChanges();
message.Add(string.Format(SocietaModelMessages.SocietaModelMessages.importOk, item.Value.Count, uploadfile.FileName, societaRepository.GetSocieta(societaId).NomeSocieta));
}
TempData["succes"] = message;
} else
{
foreach (var validationItem in validationErrors)
{
ModelState.AddModelError(validationItem.Key, validationItem.Value);
}
}
return View();
}
}
return View();
}
public ActionResult GetMessage()
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
//Apertura istanza tabelle database
using (var context = new Models.SocietaModelContainer("sdemo"))
{
var Responsabile = context.RPSoggettiPartecipantiSet.Local[0].Id;
}
////create a entry of DocumentSummaryInformation
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hssfworkbook.DocumentSummaryInformation = dsi;
////create a entry of SummaryInformation
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hssfworkbook.SummaryInformation = si;
//here, we must insert at least one sheet to the workbook. otherwise, Excel will say 'data lost in file'
//So we insert three sheet just like what Excel does
ISheet sheet1 = hssfworkbook.CreateSheet("Sheet1");
IRow row0 = sheet1.CreateRow(0);
IRow row1 = sheet1.CreateRow(1);
IRow row2 = sheet1.CreateRow(2);
IFont font1 = hssfworkbook.CreateFont();
font1.FontHeightInPoints = 28;
font1.Boldweight = (short)FontBoldWeight.Bold;
IFont font2 = hssfworkbook.CreateFont();
font2.FontHeightInPoints = 11;
font2.Boldweight = (short)FontBoldWeight.Bold;
IFont font3 = hssfworkbook.CreateFont();
font3.FontHeightInPoints = 8;
font3.Boldweight = (short)FontBoldWeight.Normal;
ICellStyle styleCenter1 = hssfworkbook.CreateCellStyle();
styleCenter1.Alignment = HorizontalAlignment.Center;
styleCenter1.VerticalAlignment = VerticalAlignment.Center;
styleCenter1.WrapText = true;
styleCenter1.SetFont(font1);
//styleCenter1.BorderBottom = BorderStyle.Thick;
//styleCenter1.BorderLeft = BorderStyle.Thick;
//styleCenter1.BorderRight = BorderStyle.Thick;
//styleCenter1.BorderTop = BorderStyle.Thick;
ICellStyle styleCenter2 = hssfworkbook.CreateCellStyle();
styleCenter2.Alignment = HorizontalAlignment.Center;
styleCenter2.VerticalAlignment = VerticalAlignment.Center;
styleCenter2.WrapText = true;
styleCenter2.SetFont(font2);
ICellStyle styleCenter3 = hssfworkbook.CreateCellStyle();
styleCenter3.Alignment = HorizontalAlignment.Center;
styleCenter3.VerticalAlignment = VerticalAlignment.Center;
styleCenter3.WrapText = true;
styleCenter3.SetFont(font3);
row0.CreateCell(0).SetCellValue("REGISTRO ATTIVITÀ DI TRATTAMENTO DEL TITOLARE");
sheet1.AddMergedRegion(new CellRangeAddress(0, 0, 0, 23));
row0.Height = 50 * 20;
row0.GetCell(0).CellStyle = styleCenter1;
row1.CreateCell(0).SetCellValue("Soggetti partecipanti al trattamento");
sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 0, 4));
row1.GetCell(0).CellStyle = styleCenter2;
row1.CreateCell(5).SetCellValue("Informazioni sulle attività di trattamento");
sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 5, 16));
row1.GetCell(5).CellStyle = styleCenter2;
row1.CreateCell(17).SetCellValue("Misure di sicurezza tecniche ed organizzative e rischi");
sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 17, 19));
row1.GetCell(17).CellStyle = styleCenter2;
row1.CreateCell(20).SetCellValue("Trasferimento verso Paese terzo (se previsto)");
sheet1.AddMergedRegion(new CellRangeAddress(1, 1, 20, 22));
row1.GetCell(20).CellStyle = styleCenter2;
row1.CreateCell(23).SetCellValue("Note lavoro");
row1.GetCell(23).CellStyle = styleCenter2;
row2.CreateCell(0).SetCellValue("Nome Società Titolare del trattamento");
row2.CreateCell(1).SetCellValue("Responsabile del trattamento (se previsto)");
row2.CreateCell(2).SetCellValue("Responsabile della protezione dei dati (se nominato)");
row2.CreateCell(3).SetCellValue("Rappresentante UE del Titolare non stabiliti nell'UE (se previsto)");
row2.CreateCell(4).SetCellValue("Contatti Contitolare");
row2.CreateCell(5).SetCellValue("Funzione Aziendale");
row2.CreateCell(6).SetCellValue("Attività di trattamento");
row2.CreateCell(7).SetCellValue("Descrizione dettagliata del trattamento");
row2.CreateCell(8).SetCellValue("Finalità del trattamento");
row2.CreateCell(9).SetCellValue("Interessati al trattamento dei dati");
row2.CreateCell(10).SetCellValue("Categoria dati");
row2.CreateCell(11).SetCellValue("Approfondimento categoria dati");
row2.CreateCell(12).SetCellValue("Base giuridica del trattamento");
row2.CreateCell(13).SetCellValue("Categoria destinatari a cui i dati personali sono stati o saranno comunicati / Società del gruppo a cui sono trasferiti i dati (se previsto)");
row2.CreateCell(14).SetCellValue("Termine cancellazione dei dati o criteri adottati");
row2.CreateCell(15).SetCellValue("Tipo di trattamento (automatizzato o non)");
row2.CreateCell(16).SetCellValue("Applicativi correlati al trattamento");
row2.CreateCell(17).SetCellValue("Descrizione delle misure di sicurezza organizzative e tecniche");
row2.CreateCell(18).SetCellValue("Descrizione del rischio per l'interessato");
row2.CreateCell(19).SetCellValue("Data breach - casi possibili");
row2.CreateCell(20).SetCellValue("Paese o Organizzazione a cui si invia");
row2.CreateCell(21).SetCellValue("Paese o Organizzazione da cui si riceve");
row2.CreateCell(22).SetCellValue("Garanzie ex art. 49 GDPR");
for (int i=0;i<23;i++)
{
row2.GetCell(i).CellStyle = styleCenter3;
}
int x = 1;
for (int i = 3; i <= 10; i++)
{
IRow row = sheet1.CreateRow(i);
for (int j = 0; j < 24; j++)
{
row.CreateCell(j).SetCellValue(x++);
row.GetCell(j).CellStyle = styleCenter3;
}
}
//Write the stream data of workbook to the root directory
FileStream file = new FileStream(@"C:\Users\buffo\Desktop\test.xls", FileMode.Create);
hssfworkbook.Write(file);
file.Close();
//try
//{
// MemoryStream bos = new MemoryStream();
// try
// {
// hssfworkbook.Write(bos);
// }
// finally
// {
// bos.Close();
// }
// b = bos.ToArray();
// Response.Clear();
// Response.AddHeader("content-disposition", "attachment;filename=test.xlsx");
// Response.Charset = "";
// Response.Cache.SetNoServerCaching();
// Response.ContentType = "application/ms-excel";
// Response.BinaryWrite(b);
//}
//catch (Exception)
//{
// message = "Download non riuscito";
// return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
//}
message = "Download eseguito";
return new JsonResult { Data = message, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
}
}