« Previous : 1 : 2 : 3 : 4 : 5 : ... 13 : Next »

[JavaScript] 숫자만 입력 받기


숫자만 입력할 수 있도록하고, min, max, maxlength등을 실시간 처리한다.


<!DOCTYPE html>
<html lang="ko-KR">
<head>

    <meta charset="UTF-8">
<meta name="format-detection" content="telephone=no">
    <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
   
    <title>숫자만 입력받기</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no, target-densitydpi=medium-dpi">

    <script src="http://dev.bokdukpan.com/resource/home/pc/js/common/jquery-1.9.1.min.js"></script>
</head>
<body>

<!-- start of :: wrap -->
<div id="wrap">
    <!-- start of :: header -->
   
숫자 : <input type="text" id="numberInput" name="numberInput"  value="" placeholder="" class="ipt"><br />
</div>
<!-- end of :: wrap-->

<script type="text/javascript">
(function($) {
$(function() {
$(document).on({'keydown' : function(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode

if ($.inArray(charCode, [46, 8, 9, 27, 13, 110, 190]) !== -1 // delete, backspace, tab, escape, enter, decimal point, period
|| (charCode == 65 && (evt.ctrlKey === true || evt.metaKey === true)) // Allow: Ctrl/cmd+A
|| (charCode == 67 && (evt.ctrlKey === true || evt.metaKey === true)) // Allow: Ctrl/cmd+C
      || (charCode == 86 && (evt.ctrlKey === true || evt.metaKey === true)) // Allow: Ctrl/cmd+V
      || (charCode == 88 && (evt.ctrlKey === true || evt.metaKey === true)) // Allow: Ctrl/cmd+X
      || (charCode >= 35 && charCode <= 39)) // Allow: home, end, left, right
      {
           return true;
  }

if ((charCode < 31 || (charCode >= 48 && charCode <= 57)))
            return true;
           
          return false;
}
,'paste' : function(evt) {
var inputRule = $(this).data('iwtInputRule');
var data = evt.originalEvent.clipboardData.getData('text/plain');

var reg = /^[0-9]+$/;
if(!reg.test(data)) {
evt.returnValue = false;
if(evt.preventDefault) evt.preventDefault();
}
}

,'keyup focusout' : function(evt) {
var inputVal = $(this).val();

$(this).val(inputVal.replace(/[^0-9]/g, ''));
var val = parseInt($(this).val()), max = $(this).attr('max'), min = $(this).attr('min');
if(!isNaN(val)) {
if(evt.type === 'focusout' && typeof min != 'undefined' && val < min) {
$(this).val(min)
}
else if(typeof max != 'undefined' && val > max) {
$(this).val(max)
}
}

var maxlength = $(this).attr('maxlength');
if(typeof maxlength != 'undefined' && $(this).val().length > maxlength) {
$(this).val($(this).val().substring(0, maxlength));
}
}
}, 'input');
  });
})(jQuery);
</script>

</body>
</html>

Posted by incree

2018/10/10 23:48 2018/10/10 23:48
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/397

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

전자정부프레임워크(스프링) 로케일 설정이 정상작동하지 않을때 다음 사항을 확인한다.
(Spring localeChangeInterceptor does not work)


1. 전자정부프레임워크 샘플에 있는 로케일 설정을 사용할때
<mvc:default-servlet-handler />
<mvc:annotation-driven />
를 사용하는 경우에는

localeChangeInterceptor를 위 태그 전에 넣어야 정상 작동한다.


<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping">
        <property name="interceptors">
            <list>
                <ref bean="localeChangeInterceptor" />
            </list>
        </property>
    </bean>
   
    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
    <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>
<mvc:default-servlet-handler />
<mvc:annotation-driven />




2. RequestMappingHandlerMapping를 사용안하고 <mvc:intercepters>....<mvc:intercepters> 에
<bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
        <property name="paramName" value="language" />
    </bean>
를 넣는다.



   
    <mvc:interceptors>
        <bean id="localeChangeInterceptor" class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">
            <property name="paramName" value="lang" />
        </bean>
        .....
    </mvc:interceptors>

    <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver">
        <property name="defaultLocale" value="ko" />
        <property name="cookieName" value="localeLang" />
        <property name="cookieMaxAge" value="-1" />
    </bean>









<mvc:annotation-driven> 이 RequestMappingHandlerMapping, RequestMappingHandlerAdapter 를 빈으로 등록해 버리기 때문에
뒤에 나오는 RequestMappingHandlerMapping bean이 추가가 안돼서 발생하는 문제 보임

Posted by incree

2018/09/28 00:14 2018/09/28 00:14
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/396

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

web.html


<script>
        function callbackFunctionName() {
            $('input[name=keyword]').focus();
        }
       
        $(function() {
            location.href = 'iwtapplink-command://initFocusWithSoftKeyboard?callback=callbackFunctionName';

        });
    </script>



android app

    public boolean shouldOverrideUrlLoading(WebView paramWebView, String paramString) {
        if (paramString.startsWith(activity.getString(R.string.appLinkIwtCommandInitFocusWithSoftKeyboard))) {
                InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);

                String callback = "callbackFunctionName";
                if(paramString.indexOf("?") > 0) {
                    try {
                        Map<String, String> queryStringMap = StringUtil.queryStringToMap(paramString.replace(activity.getString(R.string.appLinkIwtCommandInitFocusWithSoftKeyboard) + "?", ""));

                        if (!TextUtils.isEmpty(queryStringMap.get("callback"))) {
                            callback = queryStringMap.get("callback");
                        }
                    } catch (UnsupportedEncodingException uee) {

                    }
                }

                webView.loadUrl("javascript:" + callback + "();");

                return true;
            }

            return false;
        }

Posted by incree

2018/06/06 03:50 2018/06/06 03:50
, ,
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/395

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

[PHP] 환경변수를 이용한 서버 구분

php에서 환경변수를 이용한 서버 구분(상용, 개발, 스테이지등...)


1. 웹으로 접속하는 경우
아파치를 웹서버로 사용하는 경우
SetEnv를 이용

httpd.conf 또는 /httpd-vhosts.conf 에
SetEnv       SERVER_TYPE dev  추가

2. cli를 이용하는 경우 OS의 환경변수를 설정한다.
리눅스인 경우

/etc/profile 에

export SERVER_TYPE=dev 추가

3. php 스크립트를 크론탭에서 사용하는 경우
/etc/crontab 파일에

export SERVER_TYPE=dev 추가


php에서는 세가지 모두 $_SERVER['SERVER_TYPE'] 로 값을 얻을 수 있다

ex)
if($_SERVER['SERVER_TYPE'] == 'prod') {

    $dbServer = '10.1.1.1';

}
else if($_SERVER['SERVER_TYPE'] == 'dev') {
    $dbServer = '10.1.1.2';
}

Posted by incree

2018/06/05 21:32 2018/06/05 21:32
,
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/394

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

[Android]TextView Outline text

public class IATOutLineTextView extends AppCompatTextView {
public IATOutLineTextView(Context context) {
this(context, null);
}

public IATOutLineTextView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public IATOutLineTextView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);

int textColor = this.getCurrentTextColor();

TextPaint paint = this.getPaint();
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.MITER);
paint.setStrokeMiter(10);
this.setTextColor(Color.parseColor("#ff0000"));
paint.setStrokeWidth(10);
super.onDraw(canvas);
paint.setStyle(Paint.Style.FILL);
paint.setStrokeWidth(0);
this.setTextColor(textColor);
super.onDraw(canvas);
}
}

Posted by incree

2018/04/21 07:16 2018/04/21 07:16
, ,
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/392

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다



MPAndroidChart custom BarchartRenderer Example

차트에 배경 이미지 넣기
막대에 그라데이션 적용

package com.incree.mpandroidchart.custom.barchartrenderer.example;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.WindowManager;
import android.widget.SeekBar;
import android.widget.TextView;

import com.github.mikephil.charting.animation.ChartAnimator;
import com.github.mikephil.charting.buffer.BarBuffer;
import com.github.mikephil.charting.charts.BarChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.BarData;
import com.github.mikephil.charting.data.BarDataSet;
import com.github.mikephil.charting.data.BarEntry;
import com.github.mikephil.charting.formatter.IAxisValueFormatter;
import com.github.mikephil.charting.interfaces.dataprovider.BarDataProvider;
import com.github.mikephil.charting.interfaces.datasets.IBarDataSet;
import com.github.mikephil.charting.listener.OnChartValueSelectedListener;
import com.github.mikephil.charting.renderer.BarChartRenderer;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.Transformer;
import com.github.mikephil.charting.utils.Utils;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
protected BarChart mChart;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);

mChart = (BarChart) findViewById(R.id.chart1);

mChart.setDrawBarShadow(false);
mChart.setDrawValueAboveBar(true);

mChart.getDescription().setEnabled(false);

setData();

mChart.setRenderer(new MyBarChartRenderer(mChart, mChart.getAnimator(), mChart.getViewPortHandler()));
}

private void setData() {

float start = 1f;

ArrayList<BarEntry> yVals1 = new ArrayList<BarEntry>();

for (int i = 0; i < 12; i++) {
float mult = (500 + 1);
float val = (float) (Math.random() * mult);

yVals1.add(new BarEntry(i, val));
}

BarDataSet set1;

if (mChart.getData() != null &&
mChart.getData().getDataSetCount() > 0) {
set1 = (BarDataSet) mChart.getData().getDataSetByIndex(0);
set1.setValues(yVals1);
mChart.getData().notifyDataChanged();
mChart.notifyDataSetChanged();
} else {
set1 = new BarDataSet(yVals1, "The year 2017");

set1.setDrawIcons(false);

set1.setColors(ColorTemplate.MATERIAL_COLORS);

ArrayList<IBarDataSet> dataSets = new ArrayList<IBarDataSet>();
dataSets.add(set1);

BarData data = new BarData(dataSets);
data.setValueTextSize(10f);
data.setBarWidth(0.9f);

mChart.setData(data);
}
}

class MyBarChartRenderer extends BarChartRenderer {
public MyBarChartRenderer(BarDataProvider chart, ChartAnimator animator,
ViewPortHandler viewPortHandler) {
super(chart, animator, viewPortHandler);

initBuffers();
}

@Override
public void drawData(Canvas c) {
Drawable d = getResources().getDrawable(R.drawable.zzang);
d.setBounds(0, 0, c.getWidth(), c.getHeight());
d.draw(c);

super.drawData(c);
}

private RectF mBarShadowRectBuffer = new RectF();

@Override
protected void drawDataSet(Canvas c, IBarDataSet dataSet, int index) {
Transformer trans = mChart.getTransformer(dataSet.getAxisDependency());

mBarBorderPaint.setColor(dataSet.getBarBorderColor());
mBarBorderPaint.setStrokeWidth(Utils.convertDpToPixel(dataSet.getBarBorderWidth()));

final boolean drawBorder = dataSet.getBarBorderWidth() > 0.f;

float phaseX = mAnimator.getPhaseX();
float phaseY = mAnimator.getPhaseY();

// draw the bar shadow before the values
if (mChart.isDrawBarShadowEnabled()) {
mShadowPaint.setColor(dataSet.getBarShadowColor());

BarData barData = mChart.getBarData();

final float barWidth = barData.getBarWidth();
final float barWidthHalf = barWidth / 2.0f;
float x;

for (int i = 0, count = Math.min((int)(Math.ceil((float)(dataSet.getEntryCount()) * phaseX)), dataSet.getEntryCount());
i < count;
i++) {

BarEntry e = dataSet.getEntryForIndex(i);

x = e.getX();

mBarShadowRectBuffer.left = x - barWidthHalf;
mBarShadowRectBuffer.right = x + barWidthHalf;

trans.rectValueToPixel(mBarShadowRectBuffer);

if (!mViewPortHandler.isInBoundsLeft(mBarShadowRectBuffer.right))
continue;

if (!mViewPortHandler.isInBoundsRight(mBarShadowRectBuffer.left))
break;

mBarShadowRectBuffer.top = mViewPortHandler.contentTop();
mBarShadowRectBuffer.bottom = mViewPortHandler.contentBottom();

c.drawRect(mBarShadowRectBuffer, mShadowPaint);
}
}

// initialize the buffer
BarBuffer buffer = mBarBuffers[index];
buffer.setPhases(phaseX, phaseY);
buffer.setDataSet(index);
buffer.setInverted(mChart.isInverted(dataSet.getAxisDependency()));
buffer.setBarWidth(mChart.getBarData().getBarWidth());

buffer.feed(dataSet);

trans.pointValuesToPixel(buffer.buffer);

final boolean isSingleColor = dataSet.getColors().size() == 1;

if (isSingleColor) {
mRenderPaint.setColor(dataSet.getColor());
}

for (int j = 0; j < buffer.size(); j += 4) {

if (!mViewPortHandler.isInBoundsLeft(buffer.buffer[j + 2]))
continue;

if (!mViewPortHandler.isInBoundsRight(buffer.buffer[j]))
break;

if (!isSingleColor) {
// Set the color for the currently drawn value. If the index
// is out of bounds, reuse colors.
mRenderPaint.setColor(dataSet.getColor(j / 4));
}

c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],
buffer.buffer[j + 3], mRenderPaint);

if (drawBorder) {
c.drawRect(buffer.buffer[j], buffer.buffer[j + 1], buffer.buffer[j + 2],
buffer.buffer[j + 3], mBarBorderPaint);
}

Drawable d = getResources().getDrawable(R.drawable.fade_red);
d.setBounds((int)buffer.buffer[j], (int)buffer.buffer[j + 1], (int)buffer.buffer[j + 2],
(int)buffer.buffer[j + 3]);
d.draw(c);
}
}

@Override
public void drawExtras(Canvas c) {
super.drawExtras(c);
/*
Paint p = new Paint();
p.setAlpha(90);

Bitmap image = BitmapFactory.decodeResource(getResources(), R.drawable.zzang);
c.drawBitmap(image, 0, 0, p);
*/
}
}
}

https://github.com/PhilJay/MPAndroidChart


https://github.com/incree/MPAndroidChart-custom-BarChartRenderer-example












Posted by incree

2018/04/07 07:14 2018/04/07 07:14
, ,
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/389

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

Android gravity, layout_gravity dynamic programmatically

gravity : 자식 뷰를 어떻게 표시 할지
layout_gravity : 부모 뷰에 어떻게 표시할지

동적으로 추가할때 layout_gravity는 LayoutParams에 적용해야 하고
gravity는 View에 적용한다




LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
params.setGravity(Gravity.CENTER);
    setLayoutParams(params);

    setGravity(Gravity.CENTER);

Posted by incree

2018/03/20 12:01 2018/03/20 12:01
, ,
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/388

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다


전자정부프레임워크 프로젝트를 github 연동후 다음과 같은 에러가 나면
org.eclipse.jgit.api.errors.TransportException: Nothing to fetch.
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:139)
at org.eclipse.jgit.api.PullCommand.call(PullCommand.java:253)
at org.eclipse.egit.core.op.PullOperation$1.run(PullOperation.java:97)
at org.eclipse.core.internal.resources.Workspace.run(Workspace.java:2313)
at org.eclipse.egit.core.op.PullOperation.execute(PullOperation.java:128)
at org.eclipse.egit.ui.internal.pull.PullOperationUI.execute(PullOperationUI.java:139)
at org.eclipse.egit.ui.internal.pull.PullOperationUI$1.runInWorkspace(PullOperationUI.java:114)
at org.eclipse.core.internal.resources.InternalWorkspaceJob.run(InternalWorkspaceJob.java:38)
at org.eclipse.core.internal.jobs.Worker.run(Worker.java:54)
Caused by: org.eclipse.jgit.errors.TransportException: Nothing to fetch.
at org.eclipse.jgit.transport.Transport.fetch(Transport.java:1087)
at org.eclipse.jgit.api.FetchCommand.call(FetchCommand.java:130)
... 8 more


config 파일 [remote "origin"] 항목에

fetch = +refs/heads/*:refs/remotes/origin/*


를 추가한다.

이클립스에서 모든 프로젝트에 적용되게 하려면

Windows -> Preferences -> Team -> Git -> Configuration - Repository Settings 탭
-> Add Entry
Key : remote.origin.fetch
Value : +refs/heads/*:refs/remotes/origin/*

config 파일 전체 내용
[core]
symlinks = false
repositoryformatversion = 0
filemode = false
logallrefupdates = true
[remote "origin"]
url = git url
fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
remote = origin
merge = refs/heads/master



Posted by incree

2018/02/11 13:08 2018/02/11 13:08
, ,
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/386

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

안드로이드 웹뷰 액티비티를 사용하고 정상적으로 종료하지 않았을때

fabric log


Crash Insights
Heads Up!
Unable to add window -- token is not valid; is your activity running?

Details:
This crash is usually caused by your app trying to display a dialog using a previously-finished Activity as a context. For example, this can happen if an Activity triggers an AsyncTask that tries to display a dialog when it is finished, but the user navigates back from the Activity before the task is completed.

s crash is usually caused by your app trying to display a dialog using a previously-finished Activity as a context. For example, this can happen if an Activity triggers an AsyncTask that tries to display a dialog when it is finished, but the user navigates back from the Activity before the task is completed.
Resources:
1. Android – Displaying Dialogs From Background Threads
2. Error : BinderProxy@45d459c0 is not valid; is your activity running?

Fatal Exception: android.view.WindowManager$BadTokenException
Unable to add window -- token android.os.BinderProxy@d21dce2 is not valid; is your activity running?
 Raw Text
android.view.ViewRootImpl.setView (ViewRootImpl.java:890)
com.android.webview.chromium.Ap.handleJsAlert (WebViewContentsClientAdapter.java:355)
org.chromium.android_webview.AwContentsClientBridge$$Lambda$2.run (Unknown Source:3)
android.os.Handler.handleCallback (Handler.java:751)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1358)
Show all 44 Threads

이와 같은 에러가 나면서 앱이 크래쉬 되는 경우가 있다.

webview activity를 종료한 후 결제등의 화면에서 세션이 종료되는 것을 알리는 alert를 띄워줄때 발생하는 경우가 있다.

activity만 종료했기 때문이고, webview도 distory 해주면 이 에러는 해결된다.

백버튼이나 액티비티 종료 버튼을 눌러서 종료할때

다음과 같이 webview를 distory 한후 activity를 finish 한다.

@Override
public void onBackPressed() {
webView.destroy();
finish();
}


사용자 삽입 이미지



Posted by incree

2018/01/26 23:16 2018/01/26 23:16
,
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/385

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

전자정부 3.6.0에 포함된 spring 에서 기본으로 제공하는 엑셀 다운로드는

HSSFWorkbook 을 사용하기 때문에 65536 레코드가 넘어가면 에러가 발생한다.


XSSFWorkbook 형태로 다운로드 받기 위해서는 AbstractView를 직접 구현해 주어야 한다.



1. pom.xml에 poi, poi-ooxml dependency 추가


<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>


2. AbstractView 구현

package com.incree.excel;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFDataFormat;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.stereotype.Component;

@Component("listExcelView")
public class ListExcelView extends AbstractView  {
private static final String CONTENT_TYPE = "application/vnd.ms-excel";

public ListExcelView() {
setContentType(CONTENT_TYPE);
}

  /**
   * 스프링 AbstractExcelView 에 있는 함수 편리하게 쓰기 위해 추가
   */
protected XSSFCell getCell(XSSFSheet sheet, int row, int col) {
XSSFRow sheetRow = sheet.getRow(row);
if (sheetRow == null) {
sheetRow = sheet.createRow(row);
}
XSSFCell cell = sheetRow.getCell(col);
if (cell == null) {
cell = sheetRow.createCell(col);
}
return cell;
}

/**
   * 스프링 AbstractExcelView 에 있는 함수 편리하게 쓰기 위해 추가
   */
protected void setText(XSSFCell cell, String text) {
cell.setCellType(CellType.STRING); // 스프링엔 cell.setCellType(HSSFCell.CELL_TYPE_STRING); 로 돼 있지만 deprecated 됐으므로 수정
cell.setCellValue(text);
}

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
XSSFWorkbook wb = new XSSFWorkbook();
        XSSFSheet sheet = (XSSFSheet) wb.createSheet("쉬트이름");

        XSSFCell cell = null;

        XSSFDataFormat format = wb.createDataFormat();
        XSSFCellStyle style = wb.createCellStyle();
    style.setDataFormat(format.getFormat("#,###"));

int cellStartIndex = 2;

// set header information
setText(getCell(sheet, 1, 0), "셀내용");
setText(getCell(sheet, 2, 1), "셀내용2");
setText(getCell(sheet, 3, 2), "셀내용3");

               // List resultList =  (List) model.get("resultList");

..............
..............
..............


ServletOutputStream out = response.getOutputStream();
wb.write(out);

        if (out != null) out.close();
        if (wb != null) wb.close();
}
}

3. controller 구현

package com.incree.excel;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class ListController {
@RequestMapping("/listExcelDownload.do")
public ModelAndView listExcelDownload(Model model, HttpServletResponse response) throws Exception{
// List resultList = getList();

// Map<String, Object> map = new HashMap<String, Object>();
// map.put("resultList", resultList);

response.setHeader("Content-Disposition", "attachment; fileName=\"list_excel.xlsx\";");
response.setHeader("Content-Transfer-Encoding", "binary");

return new ModelAndView("listExcelView", map);
}

}

Posted by incree

2017/12/19 14:51 2017/12/19 14:51
, ,
Response
0 Trackbacks , 0 Comments
RSS :
http://www.incree.com/tc/incree/rss/response/384

Trackback URL : 이 글에는 트랙백을 보낼 수 없습니다

« Previous : 1 : 2 : 3 : 4 : 5 : ... 13 : Next »

Notices

Archives

Authors

  1. incree

Recent Trackbacks

Calendar

«   2018/10   »
  1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31      

Site Stats

Total hits:
491964
Today:
172
Yesterday:
270