You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中移除数据字符串引号与逗号的方法求助

问题描述

在React中使用react-csv实现表格数据下载功能,但用文本编辑器打开下载的CSV文件时,数据字符串出现多余的双引号和逗号,需要移除这些符号。

用户代码如下:

import { CSVLink } from "react-csv";
import Table from "@mui/material/Table";
import TableBody from "@mui/material/TableBody";
import TableCell from "@mui/material/TableCell";
import TableContainer from "@mui/material/TableContainer";
import TableHead from "@mui/material/TableHead";
import TableRow from "@mui/material/TableRow";
import Paper from "@mui/material/Paper";
import { Hidden } from "@mui/material";

const current = new Date();

const date = `${current.getFullYear().toString().slice(-2)}.${''+current.getMonth()+1}.${current.getDate()}`;
const yymmdd = `${current.getFullYear()}${''+current.getMonth()+1}.${current.getDate()}`;
const timestamp = `${current.getFullYear()}.${''+current.getMonth()+1}.${current.getDate()}`;
const yesterday = `${current.getDate()-1}.${current.getMonth()+1}.${current.getFullYear()}`;
const dynamicdate = `${current.getDate()}.${current.getMonth}.${current.getFullYear()}`;
const hourminutesecond = `${current.getHours()}:${(current.getMinutes()<10?'0':'')+current.getMinutes()}:${(current.getSeconds()<10?'0':'')+current.getSeconds()}`;

function createData(misc, status, amount, balance, standard){
  return {misc, status, amount, balance, standard}
};

const rows = [
  createData("ブラジル銀行"),
  createData(`${timestamp}  BBコーポレートバンキング   ${hourminutesecond}`),
  createData('" "'),
  createData(`""`),
  createData(`" "`),
  createData(`""`),
  createData(`"総合預金明細書"`),
  createData(`""`),
  createData("TOKYO"),
  createData(`""`),
  createData("ACCOUNT NUMBER :    480330-0"),
  createData(`""`),
  createData(`"預金残高"`),
  createData(`"                                                                                                    "`),
  createData(`"口座種目"`,'レアル','ユーロ','USドル','円'),
  createData(`"普通預金"`,`"                 "`,`"                 "`,`"                 "`,"412,000"),
  createData(`"合計残高"`,`"                 "`,`"                 "`,`"                 "`,"412,000"),
  createData(`"                                 "`,`"                 "`,`"                 "`,`"                 "`,`"                 "`),
  createData(`"明細"`),
  createData(`"                                 "`,`"                 "`,`"                 "`,`"                 "`,`"                 "`),
  createData(`"普通預金 円"`),
  createData(`"年月日"`,'摘要','元本','差引残高',''),
  createData(`"            "`,`"前残高"`,`"                 "`,`"6,467,000 "`),
  createData(`${date}`,'入金           ',`"         2,000"`,`"     6,489,000  "`),
  createData(`"            "`,`${yymmdd}-160538Deposit Card No.0077596-5 @9900 9910466 `,`"                 "`,`"                "`),
];
  
export default function Transactions() {
  return (
    <div className="px-4 sm:px-6 lg:px-8 h-screen select-none p-4">
      <div className="sm:flex sm:items-center">
        <div className="sm:flex-auto">
          <h1 className="text-xl font-semibold text-gray-900">Transactions</h1>
          <p className="mt-2 text-sm text-gray-700">
           Transactions passed through the rubilink network
          </p>
        </div>
        <div className="mt-4 sm:mt-0 sm:ml-16 sm:flex-none">
        <div className="w-20 h-10 bg-blue-600 text-center justify-center align-middle hover:bg-blue-400 cursor-pointer ease-in-out duration-300 border rounded-lg p-1">
          <CSVLink className="text-center justify-center align-middle font-semibold text-sm text-white" data={rows} filename={`${current.getFullYear()} ${(current.getMonth()<10?'0':'')+1}${current.getDate()} ${(current.getHours()<10?'0':'') + current.getHours()}${(current.getMinutes()<10?'0':'') + current.getMinutes()}週末.csv`}>
              Download
          </CSVLink>
        </div>
        </div>
      </div>
      <div className="mt-8 flex flex-col">
        <div className="-my-2 -mx-4 overflow-x-auto sm:-mx-6 lg:-mx-8">
          <div className="inline-block min-w-full py-2 align-middle md:px-6 lg:px-8">
            <div className="overflow-hidden shadow ring-1 ring-black ring-opacity-5 md:rounded-lg">
              <TableContainer component={Paper}>
                <Table sx={{ minWidth: 650 }} aria-label='transactions'>
                  <TableBody>
                    {rows.map((row) => (
                      <TableRow
                      key={row.name}
                      sx={{ '&:last-child td, &:last-child th': { border: 0 } }}
                      >
                        <TableCell headers="hidden">
                          {row.misc}
                        </TableCell>
                        <TableCell align="left" headers="hidden">
                          {row.status}
                        </TableCell>
                        <TableCell align="left" headers="">
                          {row.amount}
                        </TableCell>
                        <TableCell align="left" headers="">
                          {row.balance}
                        </TableCell>
                        <TableCell align="left" headers="">
                          {row.standard}
                        </TableCell>
                      </TableRow>
                    ),
                      
                    )}
                  </TableBody>
                </Table>
              </TableContainer>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
解决方法

1. 清理原始数据中的多余引号

你的rows数组里很多数据本身就包含手动添加的双引号(比如"総合預金明細書"),这些会被react-csv再次转义,导致导出后出现多余引号。可以写一个工具函数清理字符串首尾的双引号:

const cleanString = (str) => {
  if (typeof str === 'string') {
    return str.replace(/^"|"$/g, '').trim();
  }
  return str || ''; // 处理undefined/null
};

然后修改createData函数,自动清理每个字段:

function createData(misc = "", status = "", amount = "", balance = "", standard = ""){
  return {
    misc: cleanString(misc),
    status: cleanString(status),
    amount: cleanString(amount),
    balance: cleanString(balance),
    standard: cleanString(standard)
  }
};

2. 处理未定义字段产生的多余逗号

之前调用createData时,很多只传了1个参数,剩下的参数会变成undefined,react-csv导出时会把这些undefined转为空值,但仍会保留逗号。给createData的参数设置默认空字符串,就能避免这个问题(上面的代码已经包含了这一步)。

3. 配置react-csv的导出选项

通过CSVLink的quoted属性控制引号的生成,设置quoted={false}可以禁止给所有字段自动添加引号(如果你的数据里没有逗号等CSV特殊字符,推荐用这个):

修改后的CSVLink代码:

<CSVLink 
  className="text-center justify-center align-middle font-semibold text-sm text-white" 
  data={rows} 
  filename={`${current.getFullYear()} ${(current.getMonth()<10?'0':'')+1}${current.getDate()} ${(current.getHours()<10?'0':'') + current.getHours()}${(current.getMinutes()<10?'0':'') + current.getMinutes()}週末.csv`}
  quoted={false}
>
    Download
</CSVLink>

最终效果

经过以上修改,导出的CSV文件里不会有多余的双引号和无意义的逗号,数据和表格中显示的内容一致。

内容的提问来源于stack exchange,提问作者htrgotoh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 22:20:41