2017年1月26日木曜日

【Angular2】カスタムディレクティブでの双方向データバインド

結論:できません



でも、イベントを使えばそれっぽいことができます。

■ディレクティブ
import {Component, EventEmitter} from '@angular/core';

@Component({
    selector: 'input-directive',
    inputs: ['inputValue'],
    outputs: ['inputEvent'],
    template: `<input [(ngModel)]="year" (change)="onYearChange($event) />`

export class YearListComponent {
    inputValue: string;
    inputEvent: EventEmitter = new EventEmitter();

    constructor(public manager: ServiceManager) {
    }

    //変更イベント
    public onChange(event) {
        this.inputEvent.emit(event);
    }
}
})


■ディレクティブを呼び出すHTML
<input-directive [inputValue]="data" (inputevent)="data=$event.target.value">
</input-directive>


2017年1月18日水曜日

【C#】行列番号からExcelのアドレスへの変換

【追記】
EPPlusにメソッドがあったのでそっちを使ったほうがらくちんです。
 OfficeOpenXml.ExcelAddress.GetAddress

タイトルそのまま、行番号、列番号を引数に渡してExcelのアドレス("A1"とか)に変換する処理。
そのまんまの処理なので特に開設はなしで。
コードをまとめるためにメソッド内でDictionaryのオブジェクトを作っていますが、使うときはいい感じのところで定義してください。

        /// 
        /// 行列番号をExcelのアドレス文字列に変換
        /// 
        /// 行番号
        /// 列番号
        /// 
        public static string ConvertExcelAddressString(int row, int col)
        {
            Dictionary DicInt2Alphabet = new Dictionary()
            {
                { 1, "A" },
                { 2, "B" },
                { 3, "C" },
                { 4, "D" },
                { 5, "E" },
                { 6, "F" },
                { 7, "G" },
                { 8, "H" },
                { 9, "I" },
                { 10, "J" },
                { 11, "K" },
                { 12, "L" },
                { 13, "M" },
                { 14, "N" },
                { 15, "O" },
                { 16, "P" },
                { 17, "Q" },
                { 18, "R" },
                { 19, "S" },
                { 20, "T" },
                { 21, "U" },
                { 22, "V" },
                { 23, "W" },
                { 24, "X" },
                { 25, "Y" },
                { 26, "Z" },
            };
            string address = "";
            int colTmp = col;

            //列番号がアルファベットの数よりも大きい場合(変換後AA以上となる場合) 2桁目の文字列を先に算出
            if(colTmp > DicInt2Alphabet.Count)
            {
                address = DicInt2Alphabet[col / DicInt2Alphabet.Count];
                colTmp = colTmp % DicInt2Alphabet.Count;
            }

            //行列番号を変換
            address += DicInt2Alphabet[colTmp] + row.ToString();

            return address;
        }

LINQ to Entitiesでの文字列大小比較

LINQではint.Parseが使えないので、文字列カラムを大小比較するにはCompareToメソッドを使用する。

例はstartDateが文字列で定義されているタコなDBからデータを抽出する場合。
しかも比較対象のパラメータがint型のため、事前にStringに変換する必要あり。
#LINQではtoStringメソッドが使用できないため

string startDate = this.param.startDate.toString();
var query =
    from ticket in _context.Tickets
    where ticket.StartDate.CompareTo(startDate) >= 0
    select ticket;

2017年1月12日木曜日

Angular2でBase64のExcelファイルをAjaxを使ってダウンロードする方法

■前提
・ExcelファイルはASP.NetのWebAPIで作成
 ⇒GETメソッドでxlsxファイルをResponseで返す

■ポイント
・responseTypeでArrayBufferを指定


this.http.get("http://hogehoge.com", { responseType: ResponseContentType.ArrayBuffer })
    .subscribe(
        data => {
            var blob = new Blob([data.arrayBuffer()], { type: data.headers.get("content-type") });
            var fName: string;
            fName = decodeURI(data.headers.get("content-disposition").substring(data.headers.get("content-disposition").indexOf('=') + 1));
            //IEの場合
            if (window.navigator.msSaveBlob) {
                window.navigator.msSaveOrOpenBlob(blob, fName);
            } else {
                //それ以外の場合(Chromeしか確認していない)
                var a = document.createElement('a');
                a.download = fName;
                a.target = '_blank';
                a.href = window.URL.createObjectURL(blob);
                a.click();
            }
        }
    )

2017年1月6日金曜日

WebAPIでEPPlusで作成したExcelブックをダウンロードする手順

ASP.NetでWebAPIを使ったサーバサイド処理にて、
EPPlusで作成したExcelブックをダウンロードさせる手順。
細かいところは省略してます。

public HttpResponseMessage Get([FromUri] SagyouNumKousuParamModelGet modelParam)
{
    //レスポンスインスタンス生成
    HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.OK);

    using (ExcelPackage inputFile = new ExcelPackage(new System.IO.FileInfo(HttpContext.Current.Server.MapPath("./") + "assets\\Template.xlsx"), false))
    {
        //inputFileに対して色々と処理
        
        //Content作成
        response.Content = new ByteArrayContent(inputFile.GetAsByteArray());
        //Contentヘッダ設定
        response.Content.Headers.Add("Content-Type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.Content.Headers.Add("content-disposition", "attachment;  filename=Sample.xlsx");
    }
}

EPPlusで名前付きセルの範囲を取得する

名前が定義されているのはNamesプロパティ。
シートに対する操作なので”ExcelWorksheet.Names["hogehoge"]”としてしまいがちだがこれではダメ。

名前はWorkbookで一意となるため、”ExcelWorkbook.Names["hogehoge"]”とする。


以下サンプル。
ExcelWorkbook workBook = inputFile.Workbook;
ExcelWorksheet template = inputFile.Workbook.Worksheets["Template"];
ExcelWorksheet workSheet = inputFile.Workbook.Worksheets.Add("Sheet1");

//名前「ヘッダ」の範囲をA1にコピー
workBook.Names["ヘッダ"].Copy(workSheet.Cells[1, 1]);