How to Read and Write Excel File

Reading/writing data from/to another excel file in userform (vba)

Try below sub. Change file path and sheet name in case of your file path and sheets.

Private Sub CmdWriteToCloseBook_Click()
Dim wb As Workbook
Dim sh As Worksheet

Application.ScreenUpdating = False
Set wb = Workbooks.Open("D:\TEMP\excel.xlsx")
Set sh = wb.Sheets("Sheet1")

sh.Cells(4, 2) = Me.TextBoxG

Set sh = Nothing
wb.Close Savechanges:=True
Set wb = Nothing
Application.ScreenUpdating = True

End Sub

Is this possible to read and write on same xls sheet?

You can not read & write same file in parallel(Read-write lock). But, we can do parallel operations on temporary data(i.e. Input/output stream). Write the data to file only after closing the input stream. Below steps should be followed.

  • Open the file to Input stream
  • Open the same file to an Output Stream
  • Read and do the processing
  • Write contents to output stream.
  • Close the read/input stream, close file
  • Close output stream, close file.

Sample code:

File inputFile = new File("D://"+file_name);
File outputFile = new File("D://"+file_name);
Workbook readCopy = Workbook.getWorkbook(inputFile);
WritableWorkbook writeCopy = Workbook.createWorkbook(outputFile,readCopy);

// instructions to put content in specific rows, specific columns

readCopy.close();
inputFile.close();
writeCopy.write();
writeCopy.close();
outputFile.close();

Apache POI - read/write same excel example

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class XLSXReaderWriter {

public static void main(String[] args) {

try {
File excel = new File("D://raju.xlsx");
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook book = new XSSFWorkbook(fis);
XSSFSheet sheet = book.getSheetAt(0);

Iterator<Row> itr = sheet.iterator();

// Iterating over Excel file in Java
while (itr.hasNext()) {
Row row = itr.next();

// Iterating over each column of Excel file
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {

Cell cell = cellIterator.next();

switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "\t");
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + "\t");
break;
case Cell.CELL_TYPE_BOOLEAN:
System.out.print(cell.getBooleanCellValue() + "\t");
break;
default:

}
}
System.out.println("");
}

// writing data into XLSX file
Map<String, Object[]> newData = new HashMap<String, Object[]>();
newData.put("1", new Object[] { 1d, "Raju", "75K", "dev",
"SGD" });
newData.put("2", new Object[] { 2d, "Ramesh", "58K", "test",
"USD" });
newData.put("3", new Object[] { 3d, "Ravi", "90K", "PMO",
"INR" });

Set<String> newRows = newData.keySet();
int rownum = sheet.getLastRowNum();

for (String key : newRows) {
Row row = sheet.createRow(rownum++);
Object[] objArr = newData.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof String) {
cell.setCellValue((String) obj);
} else if (obj instanceof Boolean) {
cell.setCellValue((Boolean) obj);
} else if (obj instanceof Date) {
cell.setCellValue((Date) obj);
} else if (obj instanceof Double) {
cell.setCellValue((Double) obj);
}
}
}

// open an OutputStream to save written data into Excel file
FileOutputStream os = new FileOutputStream(excel);
book.write(os);
System.out.println("Writing on Excel file Finished ...");

// Close workbook, OutputStream and Excel file to prevent leak
os.close();
book.close();
fis.close();

} catch (FileNotFoundException fe) {
fe.printStackTrace();
} catch (IOException ie) {
ie.printStackTrace();
}
}
}

Read/write Excel file without installing anything

For starters, you may well have the driver already installed, but only for 32-bit programs, while your program is running under 64-bit (or vice versa, but that's less common).

You can force a specific environment in your .csproj file. To force 32-bit, use:

<PropertyGroup>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>

and to force 64-bit:

<PropertyGroup>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

If the driver has been installed in the other environment, your code should connect successfully.

NB. You can list the available providers for the current environment using code like the following:

using System.Data;
using System.Data.OleDb;
using System.Linq;
using static System.Console;

var oleEnum = new OleDbEnumerator();
var data =
oleEnum.GetElements()
.Rows
.Cast<DataRow>()
.Select(row => (
name: row["SOURCES_NAME"] as string,
descr: row["SOURCES_DESCRIPTION"] as string
))
.OrderBy(descr => descr);
foreach (var (name, descr) in data) {
WriteLine($"{name,-30}{descr}");
}

What if you don't have the Microsoft.ACE.OLEDB.12.0 provider in either environment? If you can convert your .xlsx file to an .xls file, you could use the Microsoft Jet 4.0 OLE DB Provider, which has been installed in every version of Windows since Windows 2000 (only available for 32-bit).

Set the PlatformTarget to x86 (32-bit) as above. Then, edit the connection string to use the older provider:

using System.Data.OleDb;

var fileName = @"C:\ExcelFile.xls";
// note the changes to Provider and the first value in Extended Properties
var connectionString =
"Provider=Microsoft.Jet.OLEDB.4.0;" +
$"Data Source={fileName};" +
"Extended Properties=\"Excel 8.0;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\"";

using var conn = new OleDbConnection(connectionString);
conn.Open();

Once you have an open OleDbConnection, you can read and write data using the standard ADO .NET command idioms for interacting with a data source:

using System.Data;
using System.Data.OleDb;

var ds = new DataSet();
using (var conn = new OleDbConnection(connectionString)) {
conn.Open();

// assuming the first worksheet is called Sheet1

using (var cmd = conn.CreateCommand()) {
cmd.CommandText = "UPDATE [Sheet1$] SET Field1 = \"AB\" WHERE Field2 = 2";
cmd.ExecuteNonQuery();
}

using (var cmd1 = conn.CreateCommand()) {
cmd1.CommandText = "SELECT * FROM [Sheet1$]";
var adapter = new OleDbDataAdapter(cmd);
adapter.Fill(ds);
}
};

NB. I found that in order to update data I needed to remove the IMEX=1 value from the connection string, per this answer.


If you must use an .xlsx file, and you only need to read data from the Excel file, you could use the ExcelDataReader NuGet package in your project.

Then, you could write code like the following:

using System.IO;
using ExcelDataReader;

// The following line is required on .NET Core / .NET 5+
// see https://github.com/ExcelDataReader/ExcelDataReader#important-note-on-net-core
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);

DataSet ds = null;
using (var stream = File.Open(@"C:\ExcelFile.xlsx", FileMode.Open, FileAccess.Read)) {
using var reader = ExcelReaderFactory.CreateReader(stream);
ds = reader.AsDataSet();
}

Another alternative you might consider is to use the Office Open XML SDK, which supports both reading and writing. I think this is a good starting point -- it shows both how to read from a given cell, and how to write information back into a cell.

How to read and write to the same excel file in Talend in the same subjob?

You can do that by add a step.

You need to output in another Excel file in the first step.

Then subjob OK

Then input your temporary file in the first one.

Then delete the temporary file.

TInputExcel (first file) -> tmap -> toutputexcel (Tempory file)
|
subjob ok
|
TInputExcel (temporary file) -> tmap -> toutputexcel (first file)
|
tfiledelete (temporary file)

Writing and Reading excel files in C#

There are few cool libraries that you can use to easy read and write excel files. You can reference them in your project and easily create/modify spreadsheets.

EPPlus
Very developer friendly and easy to use.

  • EPPlus - codeplex source
  • Simple tutorial

NOPI

  • NOPI - codeplex source

DocumentFormat.OpenXml 
It provides strongly typed classes for spreadsheet objects and seems to be fairly easy to work with.

  • DocumentFormat.OpenXml site

  • DocumentFormat.OpenXml tutorial

Open XML SDK 2.0 for Microsoft Office
Provides strongly typed classes / easy to work with.

  • Open XML SDK 2.0 - MSDN

ClosedXML - The easy way to OpenXML
ClosedXML makes it easier for developers to create (.xlsx, .xlsm, etc) files.

  • ClosedXML - repository hosted at GitHub

  • ClosedXML - codeplex source

SpreadsheetGear
*Paid - library to import / export Excel workbooks in ASP.NET

  • SpreadsheetGear site


Related Topics



Leave a reply



Submit