@@ -11,11 +11,14 @@ import (
11
11
"os"
12
12
"os/signal"
13
13
"strings"
14
+ "time"
14
15
"unicode/utf8"
15
16
)
16
17
17
18
const DefaultColumnCnt = 32
18
19
20
+ var DumpWithDataRowLimit = 10
21
+
19
22
var query = `SELECT tab.relname AS table_name
20
23
, tabdesc.description AS table_description
21
24
, col.column_name
@@ -205,13 +208,38 @@ func Dump(dbSource, targetFile string, tableNameArg, systemColumnArg string) err
205
208
_ = f .SetCellStyle (sheetName , axisComment , axisName , style )
206
209
}
207
210
211
+ records , err := selectExistsRecords (ctx , conn , tableDef )
212
+ if err != nil {
213
+ return fmt .Errorf ("select exists records: %w" , err )
214
+ }
215
+
208
216
// Add 3 empty row
209
217
vCell , _ := excelize .CoordinatesToCellName (1 + len (tableDef .Columns ), 12 )
210
218
_ = f .SetCellStyle (sheetName , "A10" , vCell , rowStyle )
211
219
_ = f .SetCellValue (sheetName , "A10" , "1" )
212
220
_ = f .SetCellValue (sheetName , "A11" , "2" )
213
221
_ = f .SetCellValue (sheetName , "A12" , "3" )
214
222
223
+ // データレコードがあれば上書き
224
+ if len (records ) > 0 {
225
+
226
+ // 枠線などのスタイルを設定
227
+ vCell , _ := excelize .CoordinatesToCellName (len (records [0 ])+ 1 , len (records )+ 9 ) // 9 is data record start position
228
+ _ = f .SetCellStyle (sheetName , "A10" , vCell , rowStyle )
229
+
230
+ for i , record := range records {
231
+ rowNum := 10 + i
232
+
233
+ vCell , _ := excelize .CoordinatesToCellName (1 , rowNum )
234
+ _ = f .SetCellValue (sheetName , vCell , fmt .Sprint (i + 1 ))
235
+
236
+ for j , cell := range record {
237
+ colNum := j + 2
238
+ vCell , _ := excelize .CoordinatesToCellName (colNum , rowNum )
239
+ _ = f .SetCellValue (sheetName , vCell , fmtCell (cell ))
240
+ }
241
+ }
242
+ }
215
243
}
216
244
217
245
f .DeleteSheet ("Sheet1" )
@@ -283,3 +311,39 @@ func Str(a any) string {
283
311
}
284
312
return a .(string )
285
313
}
314
+
315
+ func selectExistsRecords (ctx context.Context , conn * pgxpool.Pool , tableDef TableDef ) ([][]any , error ) {
316
+ rows , err := conn .Query (ctx , fmt .Sprintf (`select * from %s limit %d` , tableDef .Name , DumpWithDataRowLimit ))
317
+ if err != nil {
318
+ return nil , fmt .Errorf ("db access: %w" , err )
319
+ }
320
+ defer rows .Close ()
321
+
322
+ dataRecords := make ([][]any , 0 , DumpWithDataRowLimit )
323
+
324
+ for rows .Next () {
325
+ g := make ([]any , len (tableDef .Columns ))
326
+ for i := range g {
327
+ g [i ] = & g [i ]
328
+ }
329
+ if err := rows .Scan (g ... ); err != nil {
330
+ return nil , err
331
+ }
332
+
333
+ dataRecords = append (dataRecords , g )
334
+ }
335
+ if err := rows .Err (); err != nil {
336
+ return nil , err
337
+ }
338
+
339
+ return dataRecords , nil
340
+ }
341
+
342
+ func fmtCell (a any ) string {
343
+ switch v := a .(type ) {
344
+ case time.Time :
345
+ return v .Format ("2006-01-02 15:04:05" )
346
+ default :
347
+ return fmt .Sprint (v )
348
+ }
349
+ }
0 commit comments