I want to change this
var cell = {
v: value,
s: {alignment: {horizontal:"left"}}
};
to add hyperlink formula on 'value' like this
`{ formula:'HYPERLINK("' + mainhyperlinkurl + '","Download.Zip")' };`
In the below addcell function code sample
function addCell(range, value, row, col, ws, isHeader) {
if (range.s.r > row) range.s.r = row;
if (range.s.c > col) range.s.c = col;
if (range.e.r < row) range.e.r = row;
if (range.e.c < col) range.e.c = col;
var cell = {
v: value,
s: {alignment: {horizontal:"left"}}
};
if (cell.v == null) cell.v = '-';
var cell_ref = XLSX.utils.encode_cell({
c: col,
r: row
});
//if (typeof cell.v === 'number') cell.t = 'n';
//if (!isNaN(cell.v)) cell.t = 'n';
//else
if (typeof cell.v === 'boolean') cell.t = 'b';
else if (cell.v instanceof Date) {
cell.t = 'n';
cell.z = XLSX.SSF._table[14];
cell.v = datenum(cell.v);
} else cell.t = 's';
if(isHeader){
cell.s = {
font: {
bold:isHeader
}
};
}
ws[cell_ref] = cell;
}
waiting for your response, Thanks.
Related
How to read empty cell in excel file using POI?
When I upload Excel file, the empty cell is filled with previous cell.
like this:
this is the sample of excel file
this is the DB that the empty cell be filled with previous cell
POI VERSION
org.apache.poi
poi
4.1.2
org.apache.poi
poi-ooxml
4.1.2
code
#RequestMapping("/mng/mngSaupExcelUpload14.do")
public ModelAndView mngBizApplyExcelUpload14(MultipartHttpServletRequest request, HttpServletResponse response,
HttpSession session, INDEYearVO attach) throws IOException, ParseException {
Iterator<String> iterator = request.getFileNames();
int actResult = 0;
ModelAndView mav = new ModelAndView();
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
MultipartFile mFile = null;
while (iterator.hasNext()) {
String uploadFileName = iterator.next();
mFile = request.getFile(uploadFileName);
// String originFileName = mFile.getOriginalFilename();
// String saveFileName = originFileName;
}
XSSFWorkbook workbook = new XSSFWorkbook(mFile.getInputStream());
for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
XSSFSheet sheet = workbook.getSheetAt(sheetNum);
int rows = sheet.getPhysicalNumberOfRows();
int rowindex = 0;
int columnindex = 0;
if (sheetNum == 0) {
for (rowindex = 1; rowindex < rows; rowindex++) {
sheet = workbook.getSheetAt(0);
XSSFRow row = sheet.getRow(rowindex);
if (row != null) {
int cells = row.getPhysicalNumberOfCells();
for (columnindex = 0; columnindex <= cells; columnindex++) {
XSSFCell cell = row.getCell(columnindex);
String value = "";
if (cell == null) {
continue;
} else {
switch (cell.getCellType()) {
case FORMULA:
value = cell.getCellFormula();
break;
case NUMERIC:
//value = (int)cell.getNumericCellValue() + "";
double cellValue = cell.getNumericCellValue();
if (cellValue == Math.rint(cellValue)) {
value = String.valueOf((int) cellValue);
} else {
value = String.valueOf(cellValue);
}
break;
case STRING:
value = cell.getStringCellValue() + "";
break;
case BLANK:
value = null;
// value = cell.getBooleanCellValue() + "";
break;
case ERROR:
value = cell.getErrorCellValue() + "";
break;
default:
}
if (columnindex == 0) {
attach.setSn(Integer.parseInt(value));
}else if (columnindex == 1) {
attach.setYear(Integer.parseInt(value));
}else if (columnindex == 2) {
attach.setSigngu(value);
} else if (columnindex == 3) {
attach.setJan(Integer.parseInt(value));
} else if (columnindex == 4) {
attach.setFeb(Integer.parseInt(value));
} else if (columnindex == 5) {
attach.setMar(Integer.parseInt(value));
} else if (columnindex == 6) {
attach.setApr(Integer.parseInt(value));
} else if (columnindex == 7) {
attach.setMay(Integer.parseInt(value));
} else if (columnindex == 8) {
attach.setJne(Integer.parseInt(value));
} else if (columnindex == 9) {
attach.setJly(Integer.parseInt(value));
} else if (columnindex == 10) {
attach.setAug(Integer.parseInt(value));
} else if (columnindex == 11) {
attach.setSep(Integer.parseInt(value));
} else if (columnindex == 12) {
attach.setOct(Integer.parseInt(value));
} else if (columnindex == 13) {
attach.setNov(Integer.parseInt(value));
} else if (columnindex == 14) {
if ("false".equals(value) || "".equals(value) || "0".equals(value) || value == null ) {
attach.setDec(Integer.parseInt(""));
} else {
attach.setDec(Integer.parseInt(value));
}
}
}
}
actResult = attachFileService.fileInsertActForExcel14(attach);
}
}
}
}
if (actResult > 0) {
out.println("<script>");
out.println("alert('등록에 성공 하였습니다.');");
out.println("location.replace('" + request.getContextPath() + "attachFile.do');");
out.println("</script>");
out.flush();
out.close();
return null;
} else {
out.println("<script>");
out.println("alert('등록 중 오류가 발생했습니다.');");
out.println("location.replace('" + request.getContextPath() + "attachFile.do');");
out.println("</script>");
out.flush();
out.close();
return null;
}
}
I don't really know why empty cell is filled..
I don't think it's a problem with poi. Also check the db insert code.
And I'm developing a library that might be helpful, so I'd appreciate it if you could watch it.
https://github.com/scndry/jackson-dataformat-spreadsheet
I have a task where I need to merge more than 2 cells, with below code I am able to merge only 2 cells in the table header under word document.
var tc = new TableCell();
Text header = new Text("");
if (j == 0)
{
header = new Text("Header1");
tc.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1620" },
new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }));
}
else if (j == 1)
{
header = new Text("");
tc.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "0" }));
}
else if (j == 2)
{
header = new Text("");
tc.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "0" }));
}
else if (j == 3)
{
header = new Text("");
tc.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "0" }));
}
else if (j == 4)
{
header = new Text("Header2");
tc.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1076" },
new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }));
}
else if (j == 5)
{
header = new Text("Header3");
tc.Append(new TableCellProperties(
new TableCellWidth() { Type = TableWidthUnitValues.Dxa, Width = "1004" },
new TableCellVerticalAlignment() { Val = TableVerticalAlignmentValues.Center }));
}
Run runHeaderRun = new Run();
runHeaderRun.Append(runHeader);
runHeaderRun.Append(header);
paraHeader.Append(runHeaderRun);
tc.Append(paraHeader);
if (j == 0 || j == 2)
{
tc.TableCellProperties = new TableCellProperties();
tc.TableCellProperties.HorizontalMerge = new HorizontalMerge { Val = MergedCellValues.Restart };
}
else if (j == 1 || j == 3)
{
tc.TableCellProperties = new TableCellProperties();
tc.TableCellProperties.HorizontalMerge = new HorizontalMerge { Val = MergedCellValues.Continue };
}
headerRow.Append(tc);
table.Append(headerRow);
I get a result like this:
But I need it like this:
Although the code you posted does not compile, it looks like the problem is here:
if (j == 0 || j == 2)
{
tc.TableCellProperties = new TableCellProperties();
tc.TableCellProperties.HorizontalMerge = new HorizontalMerge { Val = MergedCellValues.Restart };
}
else if (j == 1 || j == 3)
{
tc.TableCellProperties = new TableCellProperties();
tc.TableCellProperties.HorizontalMerge = new HorizontalMerge { Val = MergedCellValues.Continue };
}
I'm assuming that j is a loop index for the columns. Your code says to start a new horizontal merge on column 0 and continue it to column 1, then restart the merge on column 2 and continue it to column 3. This is exactly what we see in the output image you provided. If you want all four cells to be merged, then the first cell should have MergedCellValues.Restart and the other three should have MergedCellValues.Continue.
Also I notice that you are creating a brand new TableCellProperties to set the HorizontalMerge in, rather than adding it to the TableCellProperties you created earlier in your code for those same cells. So that means that the properties you set earlier, like the TableCellVerticalAlignment, for example, will be lost for those cells.
I think if you change the above section of code to the following, it will fix both problems:
if (j < 4)
{
var merge = j == 0 ? MergedCellValues.Restart : MergedCellValues.Continue;
tc.TableCellProperties.HorizontalMerge = new HorizontalMerge { Val = merge };
}
My requirement.EX: date(2019-07-01) in that month 4th week i wanna particular dates based on like["1","6","7"] . ex Result like: [2019-07-28,2019-,2019-08-02,2019-08-03]
var data = {"2020-07-01",
"2020-07-02",
"2020-07-03",
"2020-07-04",
"2020-07-05",
"2020-07-06",
"2020-07-07",
"2020-07-08",
"2020-07-09",
"2020-07-10",
"2020-07-11",
"2020-07-12",
"2020-07-13",
"2020-07-14",
"2020-07-15",
"2020-07-16",
"2020-07-17",
"2020-07-18",
"2020-07-19",
"2020-07-20",
"2020-07-21",
"2020-07-22",
"2020-07-23",
"2020-07-24",
"2020-07-25",
"2020-07-26",
"2020-07-27",
"2020-07-28",
"2020-07-29",
"2020-07-30",
"2020-07-31",}
for(var n = 0; n < data.on.order.length; n++){
for(var m = 0; m < data.on.days.length; m++){
//****
if(data.on.order[n] === '1'){
firstdayMonth = moment(endOfMonth).date(0);
}else{
firstdayMonth = moment(endOfMonth).date(1);
}
// console.log('------------1',firstdayMonth)
var firstdayWeek = moment(firstdayMonth).isoWeekday(parseInt(data.on.days[m],10));
console.log('------------2 ',firstdayWeek)
// if(data.on.order[n] === "1"){
nWeeks = parseInt(data.on.order[n],10);
// }else{
// nWeeks = parseInt(data.on.order[n],10);
// }
var nextEvent = moment(firstdayWeek).add(nWeeks,'w');
// = moment(firstdayWeek).add(nWeeks,'w');
console.log('------------3',nextEvent,'---- ',nWeeks)
//****
if(nextEvent.isAfter(eventDate)){
eventDate = nextEvent;
// console.log("### eventDate: ", eventDate)
// console.log('Total dates in month ',eventDate.format("YYYY-MM-DD"))
meetings.push(eventDate.format("YYYY-MM-DD"));
}
}
}
I've tried implementing thishttps://www.paragon-inc.com/resources/blogs-posts/easy_excel_interaction_pt6 on an ASP.NET MVC 5 Application.
//SEE CODE BELOW
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
var regPIN = DB.AspNetUsers.Where(i => i.Id == user.Id).Select(i => i.registrationPIN).FirstOrDefault();
if (file != null && file.ContentLength > 0)
{
var extension = Path.GetExtension(file.FileName);
var excelFile = Path.Combine(Server.MapPath("~/App_Data/BulkImports"),regPIN + extension);
if (System.IO.File.Exists(excelFile))
{
System.IO.File.Delete(excelFile);
}
else if (file.ContentType == "application/vnd.ms-excel" || file.ContentType == "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
file.SaveAs(excelFile);//WORKS FINE
//BEGINING OF IMPORT
FileInfo eFile = new FileInfo(excelFile);
using (var excelPackage = new ExcelPackage(eFile))
{
if (!eFile.Name.EndsWith("xlsx"))//Return ModelState.AddModelError()
{ ModelState.AddModelError("", "Incompartible Excel Document. Please use MSExcel 2007 and Above!"); }
else
{
var worksheet = excelPackage.Workbook.Worksheets[1];
if (worksheet == null) { ModelState.AddModelError("", "Wrong Excel Format!"); }// return ImportResults.WrongFormat;
else
{
var lastRow = worksheet.Dimension.End.Row;
while (lastRow >= 1)
{
var range = worksheet.Cells[lastRow, 1, lastRow, 3];
if (range.Any(c => c.Value != null))
{ break; }
lastRow--;
}
using (var db = new BlackBox_FinaleEntities())// var db = new BlackBox_FinaleEntities())
{
for (var row = 2; row <= lastRow; row++)
{
var newPerson = new personalDetails
{
identificationType = worksheet.Cells[row, 1].Value.ToString(),
idNumber = worksheet.Cells[row, 2].Value.ToString(),
idSerial = worksheet.Cells[row, 3].Value.ToString(),
fullName = worksheet.Cells[row, 4].Value.ToString(),
dob = DateTime.Parse(worksheet.Cells[row, 5].Value.ToString()),
gender = worksheet.Cells[row, 6].Value.ToString()
};
DB.personalDetails.Add(newPerson);
try { db.SaveChanges(); }
catch (Exception) { }
}
}
}
}
}//END OF IMPORT
ViewBag.Message = "Your file was successfully uploaded.";
return RedirectToAction("Index");
}
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
else
{
ViewBag.Message = "Error: Your file was not uploaded. Ensure you upload an excel workbook file.";
return View();
}
}
See Picture Error
Any help would be greatly appreciated mates.
you can do like this:
public bool readXLS(string FilePath)
{
FileInfo existingFile = new FileInfo(FilePath);
using (ExcelPackage package = new ExcelPackage(existingFile))
{
//get the first worksheet in the workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets[1];
int colCount = worksheet.Dimension.End.Column; //get Column Count
int rowCount = worksheet.Dimension.End.Row; //get row count
string queryString = "INSERT INTO tableName VALUES"; //Here I am using "blind insert". You can specify the column names Blient inset is strongly not recommanded
string eachVal = "";
bool status;
for (int row = 1; row <= rowCount; row++)
{
queryString += "(";
for (int col = 1; col <= colCount; col++)
{
eachVal = worksheet.Cells[row, col].Value.ToString().Trim();
queryString += "'" + eachVal + "',";
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
if (row % 1000 == 0) //On every 1000 query will execute, as maximum of 1000 will be executed at a time.
{
queryString += ")";
status = this.runQuery(queryString); //executing query
if (status == false)
return status;
queryString = "INSERT INTO tableName VALUES";
}
else
{
queryString += "),";
}
}
queryString = queryString.Remove(queryString.Length - 1, 1); //removing last comma (,) from the string
status = this.runQuery(queryString); //executing query
return status;
}
}
Details: http://sforsuresh.in/read-data-excel-sheet-insert-database-table-c/
How to get the headers of the given Excel file in node xlsx (https://www.npmjs.com/package/xlsx) module?
Did the following in xlsx v0.16.9
const workbookHeaders = xlsx.readFile(filePath, { sheetRows: 1 });
const columnsArray = xlsx.utils.sheet_to_json(workbookHeaders.Sheets[sheetName], { header: 1 })[0];
As I could find, there's no exposed method to get headers of the Excel file from the module. So I copied few functions (With all respect to author. https://github.com/SheetJS/js-xlsx) from their source code and make that work with few changes.
function getHeaders(sheet){
var header=0, offset = 1;
var hdr=[];
var o = {};
if (sheet == null || sheet["!ref"] == null) return [];
var range = o.range !== undefined ? o.range : sheet["!ref"];
var r;
if (o.header === 1) header = 1;
else if (o.header === "A") header = 2;
else if (Array.isArray(o.header)) header = 3;
switch (typeof range) {
case 'string':
r = safe_decode_range(range);
break;
case 'number':
r = safe_decode_range(sheet["!ref"]);
r.s.r = range;
break;
default:
r = range;
}
if (header > 0) offset = 0;
var rr = XLSX.utils.encode_row(r.s.r);
var cols = new Array(r.e.c - r.s.c + 1);
for (var C = r.s.c; C <= r.e.c; ++C) {
cols[C] = XLSX.utils.encode_col(C);
var val = sheet[cols[C] + rr];
switch (header) {
case 1:
hdr.push(C);
break;
case 2:
hdr.push(cols[C]);
break;
case 3:
hdr.push(o.header[C - r.s.c]);
break;
default:
if (val === undefined) continue;
hdr.push(XLSX.utils.format_cell(val));
}
}
return hdr;
}
function safe_decode_range(range) {
var o = {s:{c:0,r:0},e:{c:0,r:0}};
var idx = 0, i = 0, cc = 0;
var len = range.length;
for(idx = 0; i < len; ++i) {
if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
idx = 26*idx + cc;
}
o.s.c = --idx;
for(idx = 0; i < len; ++i) {
if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
idx = 10*idx + cc;
}
o.s.r = --idx;
if(i === len || range.charCodeAt(++i) === 58) { o.e.c=o.s.c; o.e.r=o.s.r; return o; }
for(idx = 0; i != len; ++i) {
if((cc=range.charCodeAt(i)-64) < 1 || cc > 26) break;
idx = 26*idx + cc;
}
o.e.c = --idx;
for(idx = 0; i != len; ++i) {
if((cc=range.charCodeAt(i)-48) < 0 || cc > 9) break;
idx = 10*idx + cc;
}
o.e.r = --idx;
return o;
}
Call getHeaders function by passing the Work Sheet will return the headers array of the excel sheet.
Have a look here:
https://www.npmjs.com/package/xlsx if we go through the documentation. It says that we need to pass options By default, sheet_to_json scans the first row and uses the values as headers. With the header: 1 option, the function exports an array of arrays of values.
So the whole code goes like this:
const data = e.target.result;
const workbook = XLSX.read(data, { type: "array" });
console.log(workbook);
const firstSheetName = workbook.SheetNames[0];
const worksheet = workbook.Sheets[firstSheetName];
const options = { header: 1 };
const sheetData2 = XLSX.utils.sheet_to_json(worksheet, options);
const header = sheetData2.shift();
console.log(header); //you should get your header right here
Where e.target comes from your input.