reading excel data - excel

How to read Excel data having Number format ;;; ie hidden value in C# using spreadsheet gear.

I am not sure that I understand your question. This code writes the formatted value of a cell, the number format and the unformatted value:
using System;
namespace WriteFormattedCellWithSpreadsheetGear
{
class Program
{
static void Main(string[] args)
{
var workbook = SpreadsheetGear.Factory.GetWorkbook(#"C:\tmp\MyWorkbook.xlsx");
var worksheet = workbook.Worksheets[0];
var a1 = worksheet.Cells["A1"];
// Write the formatted data
Console.WriteLine("Text={0}", a1.Text);
// Write the number format
Console.WriteLine("NumberFormat={0}", a1.NumberFormat);
// Write the raw data
Console.WriteLine("Value={0}", a1.Value);
}
}
}

Related

Selenium datadriven testing - unable to fetch the data from the Numbers application (macOS)

I am trying to fetch the data from the Numbers application in macOS, In below code is not able to fetch the value from the cell.
public class Excel {
public static String getdata(String sheetname, int rowvalue, int cellvalue)
{
String value = "";
try {
FileInputStream fis = new FileInputStream("./Excel/Logincred.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetname);
Row r = sh.getRow(rowvalue);
Cell c = r.getCell(cellvalue);
value = c.toString();
}
catch(Exception e)
{
}
return value;
}
}
You need to append ' before each number in your excel sheet and then your code would work completely fine.
So lets say, you have a value 4 in your excel, you need to change it to '4 and then your read from excel would work

Paste into Excel locked cells

I'm creating a template for users to input data into. All I want them to be able to do is copy their data from their source and put it into Cells A21-D21. Once pasted they cannot delete or alter anything, excel is used only to be able to print. Repasting is fine as this will be a template. Ideally, users would export directly into this protected worksheet and be done with it, but instrument software just calls for excel not a specific database location.
In short, users get data from an instrument and it is saved in a format that it cannot be manipulated but neither can it be shown on any computer except what's connected to the instrument. I need this data to be put into excel but cannot be altered. Auditors can compare the Raw data to the excel if they choose.
Is there a way to have worksheet protected and select the one unlocked cell(Format Cell), A1, and then have the entire range of A21-D21 filled/pasted into?
The thinking is that people will manipulate the raw data to get the answers they want but this will limit users to paste only.
So I guess, simply, I'm hoping to find a way to allow users to copy/paste and THAT'S IT! ?
I don't know if there is a way to do what you want inside Excel, but it can be done programatically.
// Note: need to add reference to Microsoft.Office.Interop.Excel to get these namespaces
// In Visual Studio, choose Project > Add Reference > COM > Type Libraries >
// Microsoft Excel 16.0 Object Library
using Microsoft.Office.Interop.Excel;
using System.Collections.Generic;
using System.Runtime.InteropServices;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
string fileName = #"c:\users\eric.sundquist\desktop\book1.xlsx";
int worksheetNumber = 1;
List<string> contents = new List<string> { "1", "2", "3", "4" };
PasteIntoProtectedSheet(fileName, worksheetNumber, contents);
}
static void PasteIntoProtectedSheet(string fileName, int worksheetNumber,
List<string> contents)
{
Application excel = new Application();
Workbook workbook = excel.Workbooks.Open(fileName);
workbook.Sheets[worksheetNumber].Unprotect();
// Can pass in password as parameter if needed
Range range = workbook.Sheets[1].Range("A21:D21");
for (int column = 0; column < contents.Count; column++)
{
range.Cells[1, column + 1] = contents[column];
}
workbook.Sheets[worksheetNumber].Protect();
workbook.Save();
workbook.Close();
Marshal.ReleaseComObject(range);
Marshal.ReleaseComObject(workbook);
Marshal.ReleaseComObject(excel);
}
}
}

CSV generation possible with Apache POI?

I need to generate csv files and I stumbled on a module in our project itself which uses Apache POI to generate excel sheets aleady. So I thought I could use the same to generate csv. So I asked google brother, but he couldnt find anything for sure that says Apache POI can be used for CSV file generation. I was checking on the following api too and it only talks about xls sheets and not csv anywhere. Any ideas?
http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Workbook.html
Apache Poi will not output to CSV for you. However, you have a couple good options, depending on what kind of data you are writing into the csv.
If you know that none of your cells will contain csv markers such as commas, quotes, line endings, then you can loop through your data rows and copy the text into a StringBuffer and send that to regular java IO.
Here is an example of writing an sql query to csv along those lines: Poi Mailing List: writing CSV
Otherwise, rather than figure out how to escape the special characters yourself, you should check out the opencsv project
If you check official web site Apache POI, you can find lots of example there. There is also an example that shows how you can have csv formatted output by using apache POI.
ToCSV example
Basic strategy:
1) Apache Commons CSV is the standard library for writing CSV values.
2) But we need to loop through the Workbook ourselves, and then call Commons CSV's Printer on each cell value, with a newline at the end of each row. Unfortunately this is custom code, it's not automatically available in XSSF. But it's easy:
// In this example we construct CSVPrinter on a File, can also do an OutputStream
Reader reader = Files.newBufferedReader(Paths.get(SAMPLE_CSV_FILE_PATH));
CSVPrinter csvPrinter = new CSVPrinter(reader, CSVFormat.DEFAULT);
if (workbook != null) {
XSSFSheet sheet = workbook.getSheetAt(0); // Sheet #0
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
csvPrinter.print(cell.getStringCellValue()); // Call Commons CSV here to print
}
// Newline after each row
csvPrinter.println();
}
}
// at the end, close and flush CSVPrinter
csvPrinter.flush();
csvPrinter.close();
An improved and tested version of gene b's response is this:
/**
* Saves all rows from a single Excel sheet in a workbook to a CSV file.
*
* #param excelWorkbook path to the Excel workbook.
* #param sheetNumber sheet number to export.
* #param csvFile CSV file path for output.
* #throws IOException if failed to read the Excel file or create/write to a CSV file.
*/
public static void excelToCsv(String excelWorkbook, int sheetNumber, String csvFile) throws IOException {
try (Workbook workbook = WorkbookFactory.create(new File(excelWorkbook), null, true); // Read-only: true
BufferedWriter writer = new BufferedWriter(new FileWriter(csvFile));
CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.DEFAULT)) {
Sheet sheet = workbook.getSheetAt(sheetNumber);
DataFormatter format = new DataFormatter();
for (Row row : sheet) {
for (int c = 0; c < row.getLastCellNum(); c++) {
// Null cells returned as blank
Cell cell = row.getCell(c, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String cellValue = format.formatCellValue(cell);
csvPrinter.print(cellValue);
}
csvPrinter.println();
}
csvPrinter.flush();
}
}
The following improvements were made:
NullPointerException won't be thrown if a cell in an Excel Row was never edited. A blank value will be written to the CSV instead.
Excel values are rendered using DataFormatter allowing the CSV to match the visual representation of the Excel sheet.
try-with-source used for auto-close of the file objects.
The workbook is opened in the read-only mode.

apache poi how to disable external reference or external links?

I've been looking on the web for 30 minutes now and can't find any explanation about that. Here is my problem :
I wrote an application with poi to parse some data from 200 excel files or so and put some of it into a new file. I do some cell evaluation with FormulaEvaluator to know the content of the cells before choosing to keep them or not.
Now, when i test it on a test file with only values in the cells, the program works perfectly but when i use it on my pile of files I get this error :
"could not resolve external workbook name"
Is there any way to ignore external workbook references or set up the environment so that it wont evaluate formula with external references?
Because the ones I need don't contain references...
Thank you
Can you not just catch the error, and skip over that cell?
You're getting the error because you've asked POI to evaluate a the formula in a cell, and that formula refers to a different file. However, you've not told POI where to find the file that's referenced, so it objects.
If you don't care about cells with external references, just catch the exception and move on to the next cell.
If you do care, you'll need to tell POI where to find your files. You do this with the setupEnvironment(String[],Evaluator[]) method - pass it an array of workbook names, and a matching array of evaluators for those workbooks.
In order for POI to be able to evaluate external references, it needs access to the workbooks in question. As these don't necessarily have the same names on your system as in the workbook, you need to give POI a map of external references to open workbooks, through the setupReferencedWorkbooks(java.util.Map<java.lang.String,FormulaEvaluator> workbooks) method.
I have done please see below code that is working fine at my side
public static void writeWithExternalReference(String cellContent, boolean isRowUpdate, boolean isFormula)
{
try
{
File yourFile = new File("E:\\Book1.xlsx");
yourFile.createNewFile();
FileInputStream myxls = null;
myxls = new FileInputStream(yourFile);
XSSFWorkbook workbook = new XSSFWorkbook(myxls);
FormulaEvaluator mainWorkbookEvaluator = workbook.getCreationHelper().createFormulaEvaluator();
XSSFWorkbook workbook1 = new XSSFWorkbook(new File("E:\\elk\\lookup.xlsx"));
// Track the workbook references
Map<String,FormulaEvaluator> workbooks = new HashMap<String, FormulaEvaluator>();
workbooks.put("Book1.xlsx", mainWorkbookEvaluator);
workbooks.put("elk/lookup.xlsx", workbook1.getCreationHelper().createFormulaEvaluator());
workbook2.getCreationHelper().createFormulaEvaluator());
// Attach them
mainWorkbookEvaluator.setupReferencedWorkbooks(workbooks);
XSSFSheet worksheet = workbook.getSheetAt(0);
XSSFRow row = null;
if (isRowUpdate) {
int lastRow = worksheet.getLastRowNum();
row = worksheet.createRow(++lastRow);
}
else {
row = worksheet.getRow(worksheet.getLastRowNum());
}
if (!isFormula) {
Cell cell = row.createCell(row.getLastCellNum()==-1 ? 0 : row.getLastCellNum());
cell.setCellValue(Double.parseDouble(cellContent));
} else {
XSSFCell cell = row.createCell(row.getLastCellNum()==-1 ? 0 : row.getLastCellNum());
System.out.println(cellContent);
cell.setCellFormula(cellContent);
mainWorkbookEvaluator.evaluateInCell(cell);
cell.setCellFormula(cellContent);
// mainWorkbookEvaluator.evaluateInCell(cell);
//System.out.println(cell.getCellFormula() + " = "+cell.getStringCellValue());
}
workbook1.close();
myxls.close();
FileOutputStream output_file =new FileOutputStream(yourFile,false);
//write changes
workbook.write(output_file);
output_file.close();
} catch (Exception e) {
e.printStackTrace();
}
}

Hiding cell Contains in MS Excel using SpreadSheetGear?

Hey any body know how to hide cell contains using spreadsheet gear.
You can set IRange.NumberFormat to ";;;" to cause the contents of a cell to be hidden. There are also IRange.FormulaHidden, IRange.Rows.Hidden, IRange.Columns.Hidden and probably other ways to approach it that I am not thinking about. Here is some code which demonstrates these approaches:
namespace Program
{
class Program
{
static void Main(string[] args)
{
// Create a new workbook and get a reference to Sheet1!A1.
var workbook = SpreadsheetGear.Factory.GetWorkbook();
var sheet1 = workbook.Worksheets[0];
var a1 = workbook.Worksheets[0].Cells["A1"];
// Put some text in A1.
a1.Value = "Hello World!";
// Set a number format which causes nothing to be displayed.
//
// This is probably the best way to hide the contents of
// a single cell.
a1.NumberFormat = ";;;";
// Set FormulaHidden to true - must set IWorksheet.ProtectContents
// to true for this make any difference. This will not hide values
// in cells.
a1.FormulaHidden = true;
// Hide the row containing A1.
a1.Rows.Hidden = true;
// Hide the column containing A1.
a1.Columns.Hidden = true;
}
}
}

Resources