Example #1
0
// QueryForHtml
func (s Sql) QueryForHtml(q string, args []interface{}, renderArgs ...string) string {
	// parse renderArgs
	include := mcore.GetArgString("include", "", renderArgs...)
	exclude := mcore.GetArgString("exclude", "", renderArgs...)
	hasLimit := mcore.IsArgExists("limit", renderArgs...)
	limit := mcore.GetArgInt("limit", 20, renderArgs...)

	dataMap, columns, err := s.QueryForMaps(q, args...)
	if err != nil {
		return fmt.Sprintf(`<div class="error">Error: %v</div>`, err)
	}

	if len(dataMap) == 0 {
		return fmt.Sprintf(`<div class="info">No results<div>`)
	}

	sb := mcore.NewStringBuffer()
	sb.Append(`<table class="t-data-grid"><thead><tr>`)

	usedFields := mcore.GetFieldsUsed(columns, include, exclude)
	// append table header
	for _, colName := range usedFields {
		// TODO i18n col name
		sb.Appendf(`<th>%v</th>`, colName)
	}
	sb.Append(`</tr></thead><tbody>`)
	// append table body
	for i, rowMap := range dataMap {
		trClass := "odd"
		if i%2 == 0 {
			trClass = "even"
		}
		if hasLimit && i >= limit {
			break
		}
		sb.Appendf(`<tr class="%s">`, trClass)
		for _, colName := range usedFields {
			if v, ok := rowMap[colName]; ok {
				// has column
				sb.Appendf(`<td>%v</td>`, mcore.GetString(v))
			} else {
				// no value
				sb.Append(`<td></td>`)
			}
		}
		sb.Append("</tr>")
	}
	sb.Append("</tbody></table>")
	return sb.String()
}
Example #2
0
// JSONToExcel define values
// jsData should contain a array
func JSONToExcel(
	sheetName string,
	jsData []byte,
	include string,
	exclude string,
	locale string,
) (*xlsx.File, error) {
	var rows []map[string]interface{}
	err := json.Unmarshal(jsData, &rows)
	if err != nil {
		return nil, err
	}
	if len(rows) < 1 {
		return nil, fmt.Errorf("No datas found")
	}
	headMap := rows[0]
	allKeys := GetMapKeys(headMap)
	keys := mcore.GetFieldsUsed(allKeys, include, exclude)

	if sheetName == "" {
		sheetName = "Sheet1"
	}
	file := xlsx.NewFile()
	sheet, err := file.AddSheet(sheetName)
	if err != nil {
		return nil, err
	}
	// add header row
	row := sheet.AddRow()

	for _, key := range keys {
		cell := row.AddCell()
		cell.Value = mmsg.GetTableColumnLabel(locale, "", key)
	}

	// add datas
	for _, row := range rows {
		sheetRow := sheet.AddRow()
		for _, key := range keys {
			cell := sheetRow.AddCell()
			value := row[key]
			cell.SetValue(value)
		}
	}
	return file, nil
}