開発メモ

開発用のメモです。

Salesforce apex クラスで 添付ファイルを保存する。

public class ExcelController {

    public String xmlVersion {
        get { return '<?xml version="1.0"?>'; }
        set { return; }
    }
    
    public String xmlExcel {
        get { return '<?mso-application progid="Excel.Sheet"?>'; }
        set { return; }
    }
    
    public Account account {
        public  get; 
        private set; 
    }
    
    public Boolean pdf { get; set; }
    
    public ExcelController() {
        String aid = null;
        setAccountById(aid);
    }
    
    public ExcelController(ApexPages.StandardController controller) {
        String aid = controller.getId();
        if (controller.getRecord() instanceof Account) {
            setAccountById(aid);
        }
    }
    
    private void setAccountById(String aid) {
        account = [
            SELECT 
                Id, 
                Name, 
                Site,
                BillingPostalCode,
                BillingState,
                BillingCity,
                BillingStreet
            FROM Account 
            WHERE ID = :aid LIMIT 1
            ];
    }
    
    public void init() {
    }

    public void createPdf() {
        Attachment dc = new Attachment();

        PageReference excel = Page.ExcelPage;
        excel.getParameters().put('id', (String)account.id);
        excel.setRedirect(true);

        String body = excel.getContent().toString();
        
        body = body.replace('[発効日]', DateTime.now().format('yyyy年MM月dd日'));
        body = body.replace('[請求先郵便番号]', account.BillingPostalCode);
        body = body.replace('[請求先住所]', account.BillingState + account.BillingCity + '&#10;' + account.BillingStreet);
        body = body.replace('[請求先取引先]', account.Name);
        body = body.replace('[請求先担当部署]', account.Site);
        body = body.replace('[請求先担当者]'  , '');

        
        dc.Body     = Blob.valueOf(body);
// xml スプレッド 形式のため
        dc.Name     = '' + DateTime.now().format('yyyy-MM-dd') + '.xml';
        dc.ParentId = account.Id;

        List<Attachment> temp = [SELECT Id FROM Attachment WHERE Name = :dc.Name AND ParentId = :dc.ParentId LIMIT 1];
        for (Attachment a : temp) {
            dc.Id = a.Id;
        }
        upsert dc;
    }

}
Twitter: @asahina_alice