index.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. // Excel/CSV 转 JSON 工具主逻辑
  2. // 作者:AI进化论-花生
  3. // 详细中文注释,便于初学者理解
  4. // 选择器
  5. const fileInput = document.getElementById('fileInput');
  6. const fileLink = document.querySelector('a.btn-file-input');
  7. const pasteInput = document.getElementById('pasteInput');
  8. const convertBtn = document.getElementById('convertBtn');
  9. const jsonOutput = document.getElementById('jsonOutput');
  10. const errorMsg = document.getElementById('errorMsg');
  11. // 清空错误提示
  12. function clearError() {
  13. errorMsg.textContent = '';
  14. }
  15. // 显示错误提示
  16. function showError(msg) {
  17. errorMsg.textContent = msg;
  18. }
  19. // 解析CSV文本为JSON
  20. function csvToJson(csv) {
  21. const lines = csv.split(/\r?\n/).filter(line => line.trim() !== '');
  22. if (lines.length < 2) return [];
  23. const headers = lines[0].split(',');
  24. return lines.slice(1).map(line => {
  25. const values = line.split(',');
  26. const obj = {};
  27. headers.forEach((h, i) => {
  28. obj[h.trim()] = (values[i] || '').trim();
  29. });
  30. return obj;
  31. });
  32. }
  33. // 处理文件上传
  34. fileInput.addEventListener('change', function (e) {
  35. clearError();
  36. const file = e.target.files[0];
  37. if (!file) return;
  38. const reader = new FileReader();
  39. const ext = file.name.split('.').pop().toLowerCase();
  40. if (["xlsx", "xls"].includes(ext)) {
  41. // 读取Excel文件
  42. reader.onload = function (evt) {
  43. try {
  44. const data = evt.target.result;
  45. const workbook = XLSX.read(data, { type: 'binary' });
  46. // 默认取第一个sheet
  47. const sheetName = workbook.SheetNames[0];
  48. const sheet = workbook.Sheets[sheetName];
  49. const json = XLSX.utils.sheet_to_json(sheet, { defval: '' });
  50. jsonOutput.value = JSON.stringify(json, null, 2);
  51. // 生成CSV文本并填充到输入框
  52. const csv = XLSX.utils.sheet_to_csv(sheet);
  53. pasteInput.value = csv;
  54. } catch (err) {
  55. showError('Excel文件解析失败,请确认文件格式!');
  56. }
  57. };
  58. reader.readAsBinaryString(file);
  59. } else if (ext === 'csv') {
  60. // 读取CSV文件
  61. reader.onload = function (evt) {
  62. try {
  63. const csv = evt.target.result;
  64. const json = csvToJson(csv);
  65. jsonOutput.value = JSON.stringify(json, null, 2);
  66. pasteInput.value = csv;
  67. } catch (err) {
  68. showError('CSV文件解析失败,请确认内容格式!');
  69. }
  70. };
  71. reader.readAsText(file);
  72. } else {
  73. showError('仅支持Excel(.xlsx/.xls)或CSV文件!');
  74. }
  75. });
  76. // 处理转换按钮点击
  77. convertBtn.addEventListener('click', function () {
  78. clearError();
  79. // 处理粘贴内容
  80. const text = pasteInput.value.trim();
  81. if (!text) {
  82. showError('请上传文件或粘贴表格数据!');
  83. return;
  84. }
  85. // 判断是否为CSV格式
  86. if (text.includes(',') && text.includes('\n')) {
  87. try {
  88. const json = csvToJson(text);
  89. jsonOutput.value = JSON.stringify(json, null, 2);
  90. } catch (err) {
  91. showError('粘贴内容解析失败,请检查格式!');
  92. }
  93. } else {
  94. showError('仅支持CSV格式的粘贴内容!');
  95. }
  96. });
  97. // 示例数据
  98. const EXAMPLES = {
  99. simple: `姓名,年龄,城市\n张三,18,北京\n李四,22,上海`,
  100. user: `ID,用户名,邮箱\n1,alice,[email protected]\n2,bob,[email protected]\n3,charlie,[email protected]`,
  101. score: `学号,姓名,数学,语文,英语\n1001,王小明,90,88,92\n1002,李小红,85,91,87\n1003,张大伟,78,80,85`
  102. };
  103. // 绑定“选择文件”a标签点击事件,触发文件选择
  104. const fileSelectLink = document.querySelector('.btn-file-input');
  105. if (fileSelectLink) {
  106. fileSelectLink.addEventListener('click', function(e) {
  107. e.preventDefault();
  108. fileInput.click();
  109. });
  110. }
  111. // 绑定示例按钮事件(只针对.link-btn)
  112. const exampleBtns = document.querySelectorAll('.link-btn');
  113. exampleBtns.forEach(btn => {
  114. btn.addEventListener('click', function(e) {
  115. e.preventDefault();
  116. const type = btn.getAttribute('data-example');
  117. if (EXAMPLES[type]) {
  118. pasteInput.value = EXAMPLES[type];
  119. clearError();
  120. jsonOutput.value = '';
  121. // 自动触发转换
  122. convertBtn.click();
  123. }
  124. });
  125. });
  126. // 复制按钮功能
  127. const copyBtn = document.getElementById('copyBtn');
  128. if (copyBtn) {
  129. copyBtn.addEventListener('click', function() {
  130. if (!jsonOutput.value) {
  131. showError('暂无内容可复制!');
  132. return;
  133. }
  134. jsonOutput.select();
  135. document.execCommand('copy');
  136. // 复制成功效果
  137. const originalText = copyBtn.innerHTML;
  138. copyBtn.innerHTML = '<i class="fas fa-check"></i> 已复制';
  139. copyBtn.style.background = '#27ae60';
  140. copyBtn.style.color = '#fff';
  141. copyBtn.style.borderColor = '#27ae60';
  142. setTimeout(() => {
  143. copyBtn.innerHTML = originalText;
  144. copyBtn.style.background = '';
  145. copyBtn.style.color = '';
  146. copyBtn.style.borderColor = '';
  147. }, 1500);
  148. clearError();
  149. });
  150. }
  151. // 打赏按钮
  152. const donateBtn = document.querySelector('.x-donate-link');
  153. if (donateBtn) {
  154. donateBtn.addEventListener('click', function(e) {
  155. e.preventDefault();
  156. e.stopPropagation();
  157. chrome.runtime.sendMessage({
  158. type: 'fh-dynamic-any-thing',
  159. thing: 'open-donate-modal',
  160. params: { toolName: 'excel2json' }
  161. });
  162. });
  163. }
  164. // 工具市场按钮
  165. const toolMarketBtn = document.querySelector('.x-other-tools');
  166. if (toolMarketBtn) {
  167. toolMarketBtn.addEventListener('click', function(e) {
  168. e.preventDefault();
  169. e.stopPropagation();
  170. chrome.runtime.openOptionsPage();
  171. });
  172. }