ClosedXML how to freeze rows and columns when i export file - asp.net

I have implemented the code below, all headers and data are added without any problem. If he wants to block the possibility of editing individual fields or columns in the excel file that is downloaded by the user, then there is a problem, because nothing is blocked
i use for freeze columns/rows, but when i export file and i open file i can edit any fields
worksheet.SheetView.Freeze(1,3);
[HttpGet]
public IActionResult ExportAsExcel()
{
IEnumerable<Employee> employees = this.repo.GetAll<Employee>();
List<EmployeeDTO> employeeDTO = this._mapper.Map<List<EmployeeDTO>>(employees);
using (var workbook = new XLWorkbook())
{
var woorksheet = workbook.Worksheets.Add("Sheet1");
var currentRow = 1;
woorksheet.Cell(currentRow, 1).Value = "ID";
woorksheet.Cell(currentRow, 2).Value = "name";
foreach (var empDtos in employeeDTO)
{
currentRow++;
woorksheet.Cell(currentRow, 1).Value = empDtos.EmployeeId;
woorksheet.Cell(currentRow, 2).Value = empDtos.Name;
}
using (var stream = new MemoryStream())
{
workbook.SaveAs(stream);
var content = stream.ToArray();
return File(
content,
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"Employee.xlsx"
);
}
}
}

Related

AESKeySize parameter with ZipEntry doesn't seem to allow decompression/unzipping

The following code seems to mostly work fine. But as soon as I apply an encryption value (commented out code) to the ZipEntry, everything seems to fall apart. I get the following exception:
ICSharpCode.SharpZipLib.Zip.ZipException: 'The compression method for this entry is not supported'.
I'm currently at a loss trying to figure out what is wrong with the "compression method".
I've tried all of them, and setting the compression level to 0. Nothing seems to work.
Can someone help me?
using ICSharpCode.SharpZipLib.Core;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.IO;
public byte[] ZipPayload(byte[] data)
{
using (var outputStream = new MemoryStream())
using (var zipStream = new ZipOutputStream(outputStream))
{
zipStream.Password = "abc";
zipStream.SetLevel(0);
var zipEntry = new ZipEntry("ZipEntry")
{
//AESKeySize = 128,
//CompressionMethod = CompressionMethod.Stored
//CompressionMethod = CompressionMethod.Deflated
//CompressionMethod = CompressionMethod.Deflate64
//CompressionMethod = CompressionMethod.BZip2
//CompressionMethod = CompressionMethod.LZMA
//CompressionMethod = CompressionMethod.PPMd
//CompressionMethod = CompressionMethod.WinZipAES
//CompressionMethod = CompressionMethod.WinZipAES
};
zipStream.PutNextEntry(zipEntry);
var inputMemoryStream = new MemoryStream(data);
StreamUtils.Copy(inputMemoryStream, zipStream, new byte[4096]);
zipStream.CloseEntry();
zipStream.IsStreamOwner = false;
return outputStream.ToArray();
}
}
public byte[] UnzipPayload(byte[] data)
{
using (var outputStream = new MemoryStream())
using (var inputStream = new MemoryStream(data))
{
using (var zipStream = new ZipInputStream(inputStream))
{
zipStream.Password = "abc";
zipStream.GetNextEntry();
zipStream.CopyTo(outputStream);
}
return outputStream.ToArray();
}
}
It looks like in order to Unzip the Payload, you need to use something like this:
using (var zipFile = new ZipFile(stream))
{
zipFile.Password = "abc"
var zipEntry = zipFile.GetEntry("ZipEntry");
using (var zipInputStream = zipEntry.GetInputStream(zipEntry))
{
}
}

ASP.NET core with MVC folder pathing/mapping FAIL

Whenever I upload a file I want to have it automatically converted into .pdf (I am doing that using NuGet). The thing is the upload scheme is done using relative paths. I do not know what to put into these parentheses:
var wordDocument = appWord.Documents.Open(uploadedFile);
What should I replace uploadedFile with in order to work? I will leave my relative path mapping code below:
public IActionResult Index1()
{
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
[HttpPost]
public IActionResult Index1(IFormFile[] files)
{
// Iterate each files
foreach (var file in files)
{
// Get the file name from the browser
var fileName = System.IO.Path.GetFileName(file.FileName);
// Get file path to be uploaded
var filePath = Path.Combine(Directory.GetCurrentDirectory(), "upload", fileName);
// Check If file with same name exists and delete it
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
// Create a new local file and copy contents of uploaded file
using (var localFile = System.IO.File.OpenWrite(filePath))
using (var uploadedFile = file.OpenReadStream())
{
var appWord = new Application();
if (appWord.Documents != null)
{
//yourDoc is your word document
var wordDocument = appWord.Documents.Open(uploadedFile);
string pdfDocName = "pdfDocument.pdf";
if (wordDocument != null)
{
wordDocument.ExportAsFixedFormat(pdfDocName,
WdExportFormat.wdExportFormatPDF);
wordDocument.Close();
}
appWord.Quit();
}
uploadedFile.CopyTo(localFile);
}
}
ViewBag.Message = "Files are successfully uploaded";
// Get files from the server
var model = new FilesViewModel();
foreach (var item in Directory.GetFiles(Path.Combine(Directory.GetCurrentDirectory(), "upload")))
{
model.Files.Add(
new FileDetails { Name = System.IO.Path.GetFileName(item), Path = item });
}
return View(model);
}
public async Task<IActionResult> Download(string filename)
{
if (filename == null)
return Content("filename is not availble");
var path = Path.Combine(Directory.GetCurrentDirectory(), "upload", filename);
var memory = new MemoryStream();
using (var stream = new FileStream(path, FileMode.Open))
{
await stream.CopyToAsync(memory);
}
memory.Position = 0;
return File(memory, GetContentType(path), Path.GetFileName(path));
}
private string GetContentType(string path)
{
var types = GetMimeTypes();
var ext = Path.GetExtension(path).ToLowerInvariant();
return types[ext];
}
private Dictionary<string, string> GetMimeTypes()
{
return new Dictionary<string, string>
{
{".txt", "text/plain"},
{".pdf", "application/pdf"},
{".doc", "application/vnd.ms-word"},
{".docx", "application/vnd.ms-word"},
{".xls", "application/vnd.ms-excel"},
{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{".png", "image/png"},
{".jpg", "image/jpeg"},
{".jpeg", "image/jpeg"},
{".gif", "image/gif"},
{".csv", "text/csv"}
};
}

ASP.NET Core Image Resize

I'm trying to resize imagine with System.Drawing but im taking that file as IFormFile and when i use the System.Drawing its just keep warning me to about that : cannot implicitly convert type 'System.Drawing.Bitmap' to 'Microsoft.AspNetCore.Http.IFormFile' . I need to resize those photos and save them as IFormFile but i dont know how to do that.
public Task<IFormFile> ResizeImagine300x300(IFormFile file)
{
Image image = Image.FromStream(file.OpenReadStream(), true, true);
var newImage = new Bitmap(1024, 768);
using (var g = Graphics.FromImage(newImage))
{
g.DrawImage(image, 0, 0, 1024, 768);
};
return newImage;//the point where i get the error
}
Is it possible to do it in my way?
If its not possible, then which way i should follow?
Thanks for any suggestion
Edit: I wanna return as a IFormFile because i have a method which is uploading those files to my database. here is my method :
public async Task<FileRepo> FileUploadToDatabase(List<IFormFile> files)
{
foreach (var file in files)
{
var fileName = Path.GetFileNameWithoutExtension(file.FileName);
var fileExtension = Path.GetExtension(file.FileName);
_fileRepo = new FileRepo
{
FileName = fileName,
FileExtension = fileExtension,
FileType = file.ContentType,
CreatedDate= DateTime.Now
};
using (var dataStream = new MemoryStream())
{
await file.CopyToAsync(dataStream);
_fileRepo.FileData = dataStream.ToArray();
}
}
return _fileRepo;
}
After that I'm uploading that _fileRepo variable to my database like that :
var File = _fileUploader.FileUploadToDatabase(files);
var FileResult = File.Result;
FileResult.ProductID = ProductID;
_unitOfWorkFR.RepositoryFileRepo.Create(FileResult);

.NET Already Open DataReader

I get this error when running this code. I have looked for solution though I don't like the idea of using MARS as people have suggested as it may contain a lot of data, is there any other option here? Also can I edit a variable in a database without rewriting all of them as I do here, will this save server power or make no difference?
There is already an open DataReader associated with this Command which must be closed first.
public ActionResult CheckLinks(Link model)
{
var userId = User.Identity.GetUserId();
var UserTableID = db.UserTables.Where(c => c.ApplicationUserId == userId).First().ID;
foreach (var item in db.Links.Where(p => p.UserTable.ID == UserTableID))
{
string pageContent = null;
HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(item.Obdomain);
HttpWebResponse myres = (HttpWebResponse)myReq.GetResponse();
using (StreamReader sr = new StreamReader(myres.GetResponseStream()))
{
pageContent = sr.ReadToEnd();
}
string live = "";
if (pageContent.Contains(item.Obpage))
{
live = "Yes";
}
else { live = "No"; }
var link = new Link { Obdomain = item.Obdomain, ClientID = item.ClientID, Obpage = item.Obpage, BuildDate = item.BuildDate, Anchor = item.Anchor, IdentifierID = item.IdentifierID, live = (Link.Live)Enum.Parse(typeof(Link.Live), live), UserTableID = item.UserTableID };
db.Entry(link).State = EntityState.Modified;
db.SaveChanges();
}
return RedirectToAction("Index");
}
Entity Framework allows only one active command per context at a time. You should add .ToList() at the end of the following statement:
db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
So your code could look like this:
var items = db.Links.Where(p => p.UserTable.ID == UserTableID).ToList();
foreach (var item in items)

The most straightforward way to download a file in mvc

I am currently saving an excel file like so on my c drive.
public ActionResult Export()
{
try
{
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Add(System.Reflection.Missing.Value);
Excel.Worksheet worksheet = workbook.ActiveSheet;
var people = db.People.ToList();
worksheet.Cells[1, 1] = "Last Name";
worksheet.Cells[1, 2] = "First Name";
int row = 2;
foreach (var person in people)
{
worksheet.Cells[row, 1] = person.PersonFName;
worksheet.Cells[row, 2] = person.PersonLName;
row++;
}
workbook.SaveAs("c:\\test\\worksheet.xls");
workbook.Close();
Marshal.ReleaseComObject(workbook);
application.Quit();
Marshal.FinalReleaseComObject(application);
ViewBag.Result = "Done";
}
catch(Exception ex)
{
ViewBag.Result = ex.Message;
}
return File("c:\\test\\workseet.xls", "application/vnd.ms-excel", "workseet.xls");
// return View("Success");
}
I can go to c:\\test\workseet.xls and it exists there I can do what ever with it...
I am wanting to transform my method from return a view to return a file download...
I figured that it was as simple as this:
return File("c:\\test\\workseet.xls", "application/vnd.ms-excel", "workseet.xls");
However when I do this method and click the link to download, it gives me this error.
The process cannot access the file 'c:\test\workseet.xls' because it is being used by another process.
This duplicate question is just one of those that show how to use EPPlus to generate Excel files on the server side in a scaleable manner. It's actually a lot easier than using Excel interop and a lot faster. You don't even have to save the file to the disk.
public ActionResult ExportData()
{
//Somehow, load data to a DataTable
using (ExcelPackage package = new ExcelPackage())
{
var ws = package.Workbook.Worksheets.Add("My Sheet");
//true generates headers
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
//Save the workbook to a stream
var stream = new MemoryStream();
package.SaveAs(stream);
string fileName = "myfilename.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
stream.Position = 0;
return File(stream, contentType, fileName);
}
}
You can use LoadFromDataTable to fill a sheet from a data table or LoadFromCollection to load data from a collection, eg List<Sale>.
Both methods return an ExcelRange object (a range of cells) that you can use to format individual cells, rows, and columns. You can also create tables from a range and apply themes.
The duplicate goes even farther and shows how you can avoid even the MemoryStream

Resources