如何在Material-UI DataGrid中显示带千分位的美元货币值并设置表头加粗
Material-UI DataGrid 货币格式化与表头加粗实现
解决方案
1. 金额列货币格式化
针对outstanding_amount和allowed_amount列,添加valueFormatter属性,利用原生Intl.NumberFormatAPI生成带$符号和千分位的美元格式:
valueFormatter: (params) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(params.value)
2. 表头全局加粗
通过DataGrid的sx属性直接覆盖表头标题样式,实现所有列表头加粗:
sx={{ '& .MuiDataGrid-columnHeaderTitle': { fontWeight: 'bold' } }}
修改后的完整代码
// defining columns const data_cols = [ { field: 'cert_id', headerName: 'ID', width: 130 }, { field: 'cert_name', headerName: 'Certificate Name', width: 180 }, { field: 'outstanding_amount', headerName: 'Outstanding Amount', width: 150, type: 'number', // 新增货币格式化 valueFormatter: (params) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(params.value) }, { field: 'allowed_amount', headerName: 'Allowed Amount', width: 150, type: 'number', // 新增货币格式化 valueFormatter: (params) => new Intl.NumberFormat('en-US', { style: 'currency', currency: 'USD' }).format(params.value) }, { field: 'broker_city', headerName: 'Broker City', width: 150 }, { field: 'broker_state', headerName: 'Broker State', width: 150 }, { field: 'broker_country', headerName: 'Broker Country', width: 150 }, { field: 'broker_zip', headerName: 'Broker Zip', width: 150 } ]; return( <Box sx = {{ width: '70%', margin: 'auto', backgroundColor: 'lightgrey', boxShadow: 3, borderRadius: 2, padding: 2, marginTop: 5, height: 420, display: 'flex', flexDirection: 'column' }} > <div style={{ flexGrow: 1, backgroundColor: 'white', borderRadius: '4px' }}> <DataGrid rows={rows} columns={data_cols} initialState={{ pagination: { paginationModel: { pageSize: 5 } } }} pageSizeOptions={[5, 10, 25]} loading={loading} autoHeight={false} disableSelectionOnClick getRowId={(row) => row.cert_id} // 新增表头加粗样式 sx={{ '& .MuiDataGrid-columnHeaderTitle': { fontWeight: 'bold' } }} /> </div> </Box> )
补充说明
Intl.NumberFormat会自动处理千分位和货币符号,比手动拼接字符串更稳定,还支持多地区适配。- 如果需要单独设置某列表头样式,可给对应列对象添加
headerClassName属性,再通过sx定义该类的样式。
内容的提问来源于stack exchange,提问作者Deepansh Arora
相关产品推荐
相关产品推荐

