I am using the following code to edit cells of an excel file but I dont see my changes in the escel file.
using (var fs = new FileStream(reconnFileName, FileMode.Open, FileAccess.ReadWrite))
{
HSSFWorkbook template = new HSSFWorkbook(fs, true);
ISheet sheet = template.GetSheetAt(0);
int rownumber=3;
foreach(StringBuilder cardHolderValue in cardHolderValues)
{
sheet.GetRow(rownumber).Cells[2].SetCellValue(cardHolderValue.ToString());
rownumber++;
}
}
And I can't find any Save() function in it to do so. Please let me know how can I save my edits.
Look at: http://dotnetslackers.com/articles/aspnet/Create-Excel-Spreadsheets-Using-NPOI.aspx#s7-conclusion. There is a Write method to save your excel file.
template.Write(new FileStream("c:/path", FileMode.Create, FileAccess.ReadWrite));
Related
I am writing code for creating excel spreadsheet using OpenXml. But wanted to use Filestream instead of MemoryStream in SpreadSheet.Create() method.
Note: With MemoryStream working correctly but for some reasons I need to get code working with Filestream.
Generating corrupted file when writing code like:
FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate);
using (SpreadsheetDocument document =
SpreadsheetDocument.Create(fs,SpreadsheetDocumentType.Workbook))
{
//worksheet code
}
If needed I can post worksheet code.
Try to use using to ensure that the file stream will be closed.
using (FileStream fs = new FileStream(filepath, FileMode.OpenOrCreate))
{
using (SpreadsheetDocument document =
SpreadsheetDocument.Create(fs,SpreadsheetDocumentType.Workbook))
{
//worksheet code
}
}
I try to remove a sheet from an Excel file and I have tried a lots of source from Internet but I always get the same result: unreadable content.
The link of the last one: https://blogs.msdn.microsoft.com/vsod/2010/02/05/how-to-delete-a-worksheet-from-excel-using-open-xml-sdk-2-0/
I also tried this:
Sheet sheet = workbook.WorkbookPart.Workbook.Descendants<Sheet>().First(s => s.Name.Equals(sheetName));
sheet.Remove();
workbook.WorkbookPart.Workbook.Save();
Plus this:
sheet.RemoveAllChildren()
But the file is always corrupt.
Please!
UPDATE
using (MemoryStream xlsxStream = new MemoryStream())
{
using (var fileStream = File.OpenRead(templatePath))
fileStream.CopyTo(xlsxStream);
...
using (var workbook = SpreadsheetDocument.Open(xlsxStream, true, new OpenSettings { AutoSave = true }))
{
Sheet sheet = workbook.WorkbookPart.Workbook.Descendants<Sheet>().First(s => s.Name.Equals(sheetName));
sheet.Remove();
workbook.WorkbookPart.Workbook.Save();
...
A potential solution to your answer may be an empty (and not needed) CalculationChainPart. For more details see this answer
The following code is working fine for .xlsx, but it's not working for .xls. I got this error message
Can not open the package. Package is an OLE compound document. If this is an encrypted package, please supply the password
Code
string filepath = txtBrowse.Text;
FileStream stream = System.IO.File.Open(filepath, FileMode.Open, FileAccess.ReadWrite);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
FileInfo newFile = new FileInfo(filepath);
using (ExcelPackage package = new ExcelPackage(newFile))
{
string sheetName = System.DateTime.Now.ToShortDateString();
foreach (OfficeOpenXml.ExcelWorksheet sheet in package.Workbook.Worksheets)
{
// Check the name of the current sheet
if (sheet.Name == sheetName)
{
package.Workbook.Worksheets.Delete(sheetName);
break; // Exit the loop now
}
}
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(System.DateTime.Now.ToShortDateString());
}
How do I do this correctly?
EPPlus does not work with the XLS format. Only XLSX. You'll need to find a new library.
I succesfully used Tony's answer https://stackoverflow.com/a/18904633/306515 and simply convert it using Microsoft.Office.Interop.Excel and can still then use epplus
I tried to write to CSV file using CsvHelper in C#.
This is the link to the library http://joshclose.github.io/CsvHelper/
I used the code in web site.
Here is my code:
var csv = new CsvWriter(writer);
csv.Configuration.Encoding = Encoding.UTF8;
foreach (var value in valuess)
{
csv.WriteRecord(value);
}
It writes only a part of data to csv file.
Last rows were missing.
Could you please help with this.
You need to flush the stream. The Using statement will flush when out of scope.
using (TextWriter writer = new StreamWriter(#"C:\test.csv", false, System.Text.Encoding.UTF8))
{
var csv = new CsvWriter(writer);
csv.WriteRecords(values); // where values implements IEnumerable
}
when, I added this code after the loop code is working well
var csv = new CsvWriter(writer);
csv.Configuration.Encoding = Encoding.UTF8;
foreach (var value in valuess)
{
csv.WriteRecord(value);
}
writer.Close();
The problem occurred because I did not close the Connection
Assuming that writer is some kind of TextWriter, you should add a call to flush the contents before closing the writer:
writer.Flush()
If the last lines are missing, this is the most likely reason.
Adding to #greg's answer:
using (var sr = new StreamWriter(#"C:\out.csv", false, Encoding.UTF8)) {
using (var csv = new CsvWriter(sr)) {
csv.WriteRecords(values);
}
}
How can I find some value from cell and replace by new value in Excel?
I tryed this but it doesn't works:
Microsoft.Office.Interop.Excel.Application xlapp = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook wb =default(Microsoft.Office.Interop.Excel.Workbook);
wb = xlapp.Workbooks.Open(FileName.ToString());
wb.Worksheets[0].Cells.Replace("find","replace");
I would recommend you use NPOI which can be accessed either via codeplex or directly through Nuget in Visual Studio. It gives you the ability to easily upload, edit and create spreadsheets in .NET
Example of uploading a spreadsheet:
HSSFWorkbook hssfworkbook;
void InitializeWorkbook(string path)
{
//read the template via FileStream, it is suggested to use FileAccess.Read to prevent file lock.
//book1.xls is an Excel-2007-generated file, so some new unknown BIFF records are added.
using (FileStream file = new FileStream(path, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
}
You can then use the IRow and ICell collections of the spreadsheet to locate and edit the data you need before doing an export.
More examples can be found here
If interested, you can use GemBox.Spreadsheet for this, like so:
SpreadsheetInfo.SetLicense("FREE-LIMITED-KEY");
// Load your XLS, XLSX, ODS or CSV file.
ExcelFile wb = ExcelFile.Load(FileName.ToString());
ExcelWorksheet ws = wb.Worksheets[0];
// Replace all "find" occurances with "replace" text.
int row, column;
while(ws.Cells.FindText("find", out row, out column))
ws.Cells[row, column].ReplaceText("find", "replace");
// Save your XLS, XLSX, ODS or CSV file.
wb.Save(FileName.ToString());
Also you can find another searching in Excel example here.
All you have to do is replace
wb.Worksheets[0].Cells.Replace("find","replace");
with
wb.Worksheets[1].Cells.Replace("find","replace");