简体   繁体   English

如何使用Javascript使.csv文本“居中对齐”?

[英]How to make my .csv text 'center aligned' using Javascript?

I have the following JS code that satisfactorily produces a .csv file and saves it in a user specified location: 我有以下JS代码,它们可以令人满意地生成.csv文件并将其保存在用户指定的位置:

JS JS

function generateCSV() {
  var csvContent = "data:text/csv;charset=utf-8,"
  //Generates Valid CSV
  return csvContent
}

function download(filename, text) {
  var pom = document.createElement('a');
  pom.setAttribute('href', text);
  pom.setAttribute('download', filename);
  pom.click();
}

$('#downloadCSV').click(function () {
    var csvContent = generateCSV();
    download("foobar.csv", encodeURI(csvContent));
});

My problem is that some of the text is left aligned while some is right aligned when I open it in MS Excel. 我的问题是,当我在MS Excel中打开文本时,某些文本左对齐,而某些文本右对齐。 How can I uniformly center-align all text programmatically? 如何以编程方式统一对齐所有文本?

The alignment of columns in CSV documents opened in Excel is infered by the type of data. 根据数据类型推断在Excel中打开的CSV文档中的列对齐方式。 Text will be aligned differently than numbers and dates. 文本的对齐方式将不同于数字和日期。 If you want to force some alignment you can either change type of data in column (ie. you can add tabulation at the beginning of number to make it aligned like a text) or generate Excel file (xls or xlsx) 如果要强制进行某些对齐,则可以更改列中的数据类型(即,可以在数字的开头添加表格以使其像文本一样对齐)或生成Excel文件(xls或xlsx)

This is aligned to the right: 这是右对齐:

1;2;3

But this is aligned to the left: 但这是向左对齐的:

    1;  2;  3

Edit: Going back to your original question: There's no way to center data in CSV documents opened in Excel. 编辑:回到您的原始问题:无法在Excel中打开的CSV文档中居中数据。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM