LoginSignup
3
0

More than 3 years have passed since last update.

SOQLの結果をCSVファイルとして保存するApexバッチ

Posted at

さくっとSOQLの内容をcsvファイル化できればいいなと思って探していると
いいサイトがありました。

早速、chatterの投稿を抜き出すcsvファイル作成バッチを作ってみました。

public class CrearFeedItemCsvBatch implements Database.Batchable<sObject>, Database.Stateful {
// *************************************************
// FeedItemを抽出してCSVファイルを作成する
// K.Otsubo 2020/09/26
//
//
// CrearFeedItemCsvBatch bat = new CrearFeedItemCsvBatch();
// ID jobId = Database.executeBatch(bat);
//
// *************************************************

public CrearFeedItemCsvBatch () {
}

public String csvColumnHeader;
public List<String> csvRowValues = new List<String>();

public Database.QueryLocator start(Database.BatchableContext BC){
//ここでParentIdを指定してください
String query = 'select Id,Title, Body,InsertedBy.Name,CreatedDate,ParentId from FeedItem where ParentId=\'005100000095q5sAAA\' ';
return Database.getQueryLocator(query);
}


public void execute(Database.BatchableContext BC, List<sObject> scope){
//Process retrieved SetupAuditTrail records and format field values.
for(FeedItem currFeed : (List<FeedItem>) scope){
//csvColumnHeader = 'Id, Title, Body, Create User Name, LastEditDate , ParentId\n';
String Ids = currFeed.Id != null ? currFeed.Id : '';
String Title = currFeed.Title != null ? String.valueOf(currFeed.Title).escapeCsv() : '';
String Body = currFeed.Body != null ? String.valueOf(currFeed.Body).escapeCsv() : '';
String CreateUser = currFeed.InsertedBy.Name != null ? String.valueOf(currFeed.InsertedBy.Name).escapeCsv() : '';
String formattedDate = currFeed.CreatedDate.format('M/d/yyyy h:mm:ss a z');
String pIds = currFeed.ParentId != null ? currFeed.ParentId : '';

String rowStr = Ids + ',' + Title + ',' + Body + ',' + CreateUser + ','+ formattedDate + ',' + pIds;
csvRowValues.add(rowStr);
}
}

public void finish(Database.BatchableContext BC){
List<Folder> folders = [SELECT Id, Name FROM Folder WHERE Name = 'Sales Tools'];

if(!folders.isEmpty()){
String documentName = 'FeedItem-'+ Datetime.now();
csvColumnHeader = 'Id, Title, Body, Create User Name, CreatedDate , ParentId\n';
String csvFile = csvColumnHeader + String.join(csvRowValues,'\n');
System.debug('******** csvFile=' + csvFile);
Document doc = new Document(Name = documentName, Body = Blob.valueOf(csvFile), FolderId = folders[0].Id, Type = 'csv', ContentType='application/vnd.ms-excel');
insert doc;
}
}

}

実行は、開発者コンソールで
Debug->Open Execute Anonymous windowで
CrearFeedItemCsvBatch bat = new CrearFeedItemCsvBatch();
ID jobId = Database.executeBatch(bat);
と入力してExecuteすれば、このバッチ処理が走ります。

csvファイルはclassicのドキュメントのsales toolsの中にできます。

ただ、csvファイルはUTF-8で作成されていますので
Excelでそのまま開くと日本語が文字化けします。
別途UTF-8が使えるテキストエディタで開いて、文字コードCP-932で保存すれば
Excelで開いても文字化けしなくなります。

ApexでUTF-8からCP-932に変換する方法はあるにはあるのですが、
(正確にはCP-932をUTF-8に変換)
1文字ずつ変換するのでヒープサイズの制限でエラーになりやすいです。
Apexでは制限があるので、実際にはコントローラ(Java Script)内で行っています。
ただし、今回は画面を作らずApexだけなので、文字コード変換は割愛です。

3
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
0