How to read both .xsl and .xlsx using POI? - xssf

I have tried POI versions
1.poi-src-3.9-20121203 also with
2.poi-bin-3.10-beta2-20130904
But not able to read .xls file
Getting below error
"
org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException: Package should contain a content type part [M1.13]"
Note:I am able to read .xlsx file.

This is for .xlsx
try {
// Get the workbook object for XLSX file
XSSFWorkbook wBook = new XSSFWorkbook(new FileInputStream(path));
// Get first sheet from the workbook
XSSFSheet sheet = (XSSFSheet) wBook.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
// Iterate through each rows from first sheet
Iterator<org.apache.poi.ss.usermodel.Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
StringBuffer data = new StringBuffer();
row = (XSSFRow) rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
int count = 0;
while (cellIterator.hasNext()) {
count++;
cell = (XSSFCell) cellIterator.next();
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
data.append(cell.getRawValue()+ ";");
}else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)
{
data.append(cell.getBooleanCellValue() + ";");
} else if(cell.getCellType() == Cell.CELL_TYPE_STRING)
{
data.append(cell.getStringCellValue() + ";");
}
else if(cell.getCellType() == Cell.CELL_TYPE_BLANK)
{
data.append("" + ";");
}
else
{
data.append(cell + ";");
}
}
String finalStr = data.toString().substring(0, (data.length()-1));
System.out.print(finalStr);
}
} catch (Exception ioe) {
ioe.printStackTrace();
}
Thia is for .xls
try {
// Get the workbook object for XLS file
HSSFWorkbook wBook = new HSSFWorkbook(new FileInputStream(path));
// Get first sheet from the workbook
HSSFSheet sheet = (HSSFSheet) wBook.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
// Iterate through each rows from first sheet
Iterator<org.apache.poi.ss.usermodel.Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
StringBuffer data = new StringBuffer();
row = (HSSFRow) rowIterator.next();
// For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
int count = 0;
while (cellIterator.hasNext()) {
count++;
cell = (HSSFCell) cellIterator.next();
if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC)
{
data.append(cell.getRawValue()+ ";");
}else if(cell.getCellType() == Cell.CELL_TYPE_BOOLEAN)
{
data.append(cell.getBooleanCellValue() + ";");
} else if(cell.getCellType() == Cell.CELL_TYPE_STRING)
{
data.append(cell.getStringCellValue() + ";");
}
else if(cell.getCellType() == Cell.CELL_TYPE_BLANK)
{
data.append("" + ";");
}
else
{
data.append(cell + ";");
}
}
String finalStr = data.toString().substring(0, (data.length()-1));
System.out.print(finalStr);
}
} catch (Exception ioe) {
ioe.printStackTrace();
}

Try using org.apache.poi.ss.usermodel.Workbook. It can be used for both .xls and .xlsx file
Workbook workbook = null;
if (suffix.equalsIgnoreCase("xls")) {
workbook = (Workbook) new HSSFWorkbook(new POIFSFileSystem(
new FileInputStream(assetFile)));
} else if (suffix.equalsIgnoreCase("xlsx")) {
InputStream inp = new FileInputStream(assetFile);
workbook = new XSSFWorkbook(inp);
inp.close();
}

You need poi-ooxml to read xlsx format too.
Add this Maven dependency
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
For xls use
Workbook = new HSSFWorkbook(new FileInputStream(new File("fileName")));
For xlsx use
Workbook = workbook = new XSSFWorkbook(new FileInputStream(new File("fileName")));
If you don't know the file format before reading and sometimes finding .xls or .xlsx file extension may not be always good enough to find the actual file format. In that case do like this
Workbook workbook;
try {
workbook = new HSSFWorkbook(new FileInputStream(new File("fileName")));
System.out.println(" Reading XLS file");
} catch (OfficeXmlFileException e) {
System.out.println(" Reading XLSX file");
workbook = new XSSFWorkbook(new FileInputStream(new File("fileName")));
}
Rest is all the same .xls and .xlsx
An easier way to create workbook by autodetecting the input is
Workbook workbook = WorkbookFactory.create(new File("fileName"));

Related

How to ignore first row (header row) on insert using PhpOffice\PhpSpreadsheet

I am looking for a way to ignore first row which is the header row when inserting data into mysql database using PhpOffice\PhpSpreadsheet.I have followed this but not workingSkip First Row in PHPSpreadsheet ImportMy problem is how to ignore the header row?
Below is my clean code...
use Phppot\DataSource;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
require_once ('./vendor/autoload.php');
if (isset($_POST["import"])) {
$allowedFileType = [
'application/vnd.ms-excel',
'text/xls',
'text/xlsx',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
];
if (in_array($_FILES["file"]["type"], $allowedFileType)) {
$date = date('Y-m-d');
$targetPath = 'uploads/'.$date." ".$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new \PhpOffice\PhpSpreadsheet\Reader\Xlsx();
if($Reader) {
$Reader->setReadDataOnly(true);
$spreadSheet = $Reader->load($targetPath);
$sheetData = $spreadSheet->getActiveSheet()->toArray();
// Loop through the rows from xlsx file for insert
foreach($sheetData as $row) {
// get columns in a contigeous order from xlsx file
$regno = isset($row[0]) ? $row[0] : "";
$fullname = isset($row[1]) ? $row[1] : "";
$course = isset($row[2]) ? $row[2] : "";
$status = 1;
$pin = strtoupper(substr(md5(mt_rand()), 0, 10));
// Insert into db
$fieUploaded = $conn->itStudentsFileUpload($regno,$fullname,$course,$pin,$current_session,$status);
// If all is well send success message
if ($fieUploaded) {
echo "Success";
}
}
}
} else {
$type = "error";
$message = "Invalid File Type. Upload Excel File.";
}
}
After several tests, I solve the problem as follows:
class FirstRowFilter implements \PhpOffice\PhpSpreadsheet\Reader\IReadFilter
{
public function readCell($column, $row, $worksheetName = '') {
// Return true for rows after first row
return $row > 1;
}
}
$Reader = \PhpOffice\PhpSpreadsheet\IOFactory::createReader("Xlsx");
$filterRow = new FirstRowFilter();
$Reader->setReadFilter($filterRow);
$spreadSheet = $Reader->load($targetPath);
$sheetData = $spreadSheet->getActiveSheet()->toArray();
Note:
If you have additional fields that are not from the excel file eg. date, you need to check for emptiness of the first row from the excel file and then insert if not empty to ignore inserting empty values.

Multiple Excel upload error in ExcelPackage EPPlus

public ActionResult ExcelFile(IEnumerable < HttpPostedFileBase > excelFile) {
try {
if (excelFile != null) {
foreach(var singleExcel in excelFile) {
string path = "~/ExcelFolder/";
singleExcel.SaveAs(Server.MapPath(path + singleExcel.FileName));
using(FileStream fs = new FileStream(Server.MapPath(path + singleExcel.FileName), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using(ExcelPackage package = new ExcelPackage(fs)) {
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
int startRowNumber = sheet.Dimension.Start.Row;
int endRowNumber = sheet.Dimension.End.Row;
int startColumnNumber = sheet.Dimension.Start.Column;
int endColumnNumber = sheet.Dimension.End.Column;
if (endColumnNumber > 26) {
for (int currentColumnNumber = endColumnNumber; startColumnNumber < currentColumnNumber; currentColumnNumber--) {
var cellValue = sheet.Cells[startRowNumber, currentColumnNumber].Value ? .ToString();
if (!string.IsNullOrWhiteSpace(cellValue)) {
if (cellValue == "延人公里小計") {
sheet.DeleteColumn(currentColumnNumber);
sheet.Cells[1, currentColumnNumber].Value = "小計";
//return fsr;
package.SaveAs(
new FileInfo(# "C:\Users\leon0944\Desktop\123\" + singleExcel.FileName));
break;
}
}
}
}
}
}
}
Hello,when I upload many Excel to the file then read every single Excel to do someting.then i got error in ExcelPackage package = new ExcelPackage(fs) this row
error message :System.Runtime.InteropServices.COMException: HRESULT:
0x8003001D (STG_E_WRITEFAULT)
sometime is working normally sometime I got error,Please tell me How Can I fix this. The problem existed for several days.

MVC Import .csv

Controller
[HttpPost]
public ActionResult Import(HttpPostedFileBase excelFile)
{
if (excelFile == null || excelFile.ContentLength == 0)
{
ViewBag.Error = "Please select a excel file<br>";
return View("Index");
}
else
{
if (excelFile.FileName.EndsWith("xls") || excelFile.FileName.EndsWith("xlsx") || excelFile.FileName.EndsWith("csv"))
{
string fileName = Path.GetFileName(excelFile.FileName);
string path = Path.Combine(Server.MapPath("~/Content"), fileName);
//string path = Server.MapPath("~/Content/" + excelFile.FileName);
if (System.IO.File.Exists(path))
System.IO.File.Delete(path);
excelFile.SaveAs(path);
//Read data from excel file
MExcel.Application application = new MExcel.Application();
MExcel.Workbook workbook = application.Workbooks.Open(path);
MExcel.Worksheet worksheet = workbook.ActiveSheet;
MExcel.Range range = worksheet.UsedRange;
List<PH> publicholidays = new List<PH>();
for (int row = 0; row <= range.Rows.Count; row++)
{
PH ph = new PH();
ph.Subject = ((MExcel.Range)range.Cells[row, 1]).Text;
ph.StartDate = ((MExcel.Range)range.Cells[row, 2]).Text;
ph.EndDate = ((MExcel.Range)range.Cells[row, 4]).Text;
publicholidays.Add(ph);
}
ViewBag.Publicholidays = publicholidays;
return View("Success");
}
else
{
ViewBag.Error = "Incorrect file type<br>";
return View("Index");
}
}
}
I want to import a .csv file but why doesn't it work while when i try to import a normal .xls files, it works? Is there something wrong with my code or is it that I can't import .csv files this way?

How to reuse j2me kxml parser?

I am useing kxml parser for my j2me application. I am reading the file from phone memory and parsing the xml file to display the data(have various level of filter). On each filter i need to read the data from this file. For first time i created the parser and every time i re-assign this parser1(reference-original) to the paerser2(used to parse data). For first time i got the correct answer, but second time i haven't got the file content it shows null as data.
Here is my code:
FileConnection fc = (FileConnection)Connector.open(rmsObj.rmsData.elementAt(0).toString());
InputStream in = fc.openInputStream();
InputStreamReader is = new InputStreamReader(in);
commonAppObj.externParser = new XmlParser(is);
commonAppObj class file.
protected void fileread() {
try {
if(externParser != null){
parser = externParser;
fileparser(parser);
}else{
InputStream in = this.getClass().getResourceAsStream(this.dataBase);
InputStreamReader is = new InputStreamReader(in);
parser = new XmlParser(is);
fileparser(parser);
}
} catch (IOException ioe) {
} finally {
parser = null;
}
}
private void fileparser(XmlParser parser){
try {
ParseEvent event = null;
dataflag = 0;
dataflagS = 0;
System.out.println("findtags = " + findtags);
while (((event = parser.read()).getType() != Xml.END_DOCUMENT) && (dataflag != 1)) {
if (event.getType() == Xml.START_TAG) {
String name = event.getName();
if (name != null && name.equals(findtags)) {
dataflag = 0;
parseAddressTag(parser);
}
name = null;
}
event = null;
}
} catch (IOException ioe) {
} finally {
parser = null;
}
}
}
If your InputStream returns true in a call to markSupported you may reset it at the end of fileparser method, but first you need to call mark right after creating it.
if (in.markSupported()) {
in.mark(in.available());
}

Read Image stored in Oracle using Long DataType

I want to read the image stored in Oracle Long datatype.
Number of images are stored in a remote Oracle database in a column with datatype long. I just need to retrieve those images and show them on my aspx page.
I could retrieve the image from database but when tried to caste it to byte array, it threw error that, string can not be converted to byte[]'.
Anybody have any suggestions on how to retrieve these images stored in long column in database.
byte[] signatureBlobReceived = cls_TBL_BROKER_BL.GetInstance().GetSignatureBlobFromAccountNumber_BL(strCRNnumber);
return File(signatureBlobReceived, "image/jpeg");
public byte[] GetSignatureBlobFromAccountNumber_BL()
{
object SignatureBlob = null;
Database db = DatabaseFactory.CreateDatabase("imageConnectionString");
DbCommand dbc = db.GetSqlStringCommand(ConfigurationSettings.AppSettings["signqry"].ToString());
dbc.CommandType = CommandType.Text;
SignatureBlob = db.ExecuteScalar(dbc);
byte[] array = Encoding.ASCII.GetBytes(Convert.ToString(SignatureBlob));
string aa = string.Empty;
return array;
}
Query used is:
<add key="signqry" value="SELECT image FROM table1"/> `
Try this (odp.net)
string connStr = "User Id=user;Password=pwd;Data Source=mySID;";
OracleConnection _conn = new OracleConnection(connStr);
_conn.Open();
string sel = #"select long_raw_col from long_raw_test";
OracleCommand cmd = new OracleCommand(sel, _conn);
cmd.InitialLONGFetchSize = 5000;
OracleDataReader reader = cmd.ExecuteReader();
int rows = 0;
// loop through rows from table
while (reader.Read())
{
rows++;
byte[] buf = new byte[5000];
long bytesRead = reader.GetBytes(reader.GetOrdinal("long_raw_col"), 0, buf, 0, 5000);
FileStream fs = new FileStream("C:\\test\\test_long" + rows + ".dat", FileMode.Create);
fs.Write(buf, 0, (int)bytesRead);
fs.Close();
Console.WriteLine("Row " + rows + ": Read " + bytesRead + " bytes from table, see test_long" + rows + ".dat");
}
This example just reads the long raw data from Oracle into a byte array, then outputs to a file. Note the InitalLONGFetchSize > 0.
I use this class :my database is informix and the images are stored in Byte type .Hope this can help you.
public class MyPhoto
{
public static Stream RetrievePhoto()
{
DBConnection DAL_Helper = new DBConnection(ConfigurationSettings.AppSettings["connection"].ToString());
Byte[] myByteBuff;
Stream myImgStream;
string qry = "----------";
DataTable dt = DAL_Helper.Return_DataTable(qry);
try
{
if (dt.Rows.Count > 0)
{
if (!string.IsNullOrEmpty(dt.Rows[0][0].ToString()))
{
myByteBuff = (Byte[])((object)(dt.Rows[0][0]));
myImgStream = new MemoryStream(myByteBuff);
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
else
{
myImgStream = RetrievePhotoNoProfile();
}
}
catch (Exception ex)
{
myImgStream = RetrievePhotoNoProfile();
}
return myImgStream;
}
public static byte[] StreamToByteArray(Stream stream)
{
if (stream is MemoryStream)
{
return ((MemoryStream)stream).ToArray();
}
else
{
return ReadFully(stream);
}
}
public static byte[] ReadFully(Stream input)
{
byte[] buffer = new byte[input.Length];
using (MemoryStream ms = new MemoryStream())
{
int read;
while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, read);
}
return ms.ToArray();
}
}
private static Stream RetrievePhotoNoProfile()
{
string noprofileimgPath = HttpContext.Current.Server.MapPath("~/images/noprofile.png");
System.IO.FileStream fs = new System.IO.FileStream(noprofileimgPath, System.IO.FileMode.Open, FileAccess.Read);
byte[] ba = new byte[fs.Length];
fs.Read(ba, 0, (int)fs.Length);
Stream myImgStream = new MemoryStream(ba);
fs.Close();
return myImgStream;
}
public static Image byteArrayToImage(byte[] byteArrayIn)
{
MemoryStream ms = new MemoryStream(byteArrayIn);
Image returnImage = Image.FromStream(ms);
return returnImage;
}
}

Resources