如何设置Excel列类型和格式? [英] How do I set Excel column types and formatting?

查看:169
本文介绍了如何设置Excel列类型和格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数据从CxDBGrid导出到Excel文件。
我可以创建文件并在其中复制数据,但是我对列格式化感到困扰。由于我从数据库中提取数据,因此我希望电子表格反映出类型:NUMBER,VARCHAR2,DATE等。
我直观地创建了一个宏,去寻找VBA代码,并将其复制到Delphi项目中:

  sheet.Columns [K + 2] .NumberFormat:='0,000'; // Number 
sheet.Columns [K + 2] .NumberFormat:='@'; // Text
sheet.Columns [K + 2] .NumberFormat:='m / d / yyyy'; //日期

数字格式化大多数时间都可以正常工作,但其他两个没有。
当我打开生成的文件时,文本列显示为自定义类型,每个单元格显示-64。如果我去编辑一个单元格,那么正确的值实际上在那里。
日期是另一个问题:数据库的格式是dd / mm / yyyy,如果我按原样将它提供给Excel,那么它就会被搞砸了。我尝试设置正确的格式,但是Excel不能识别它。



任何线索?



我'm也设置列宽。

解决方案

问题是分配的值是Unicode字符串。尝试这样:

  sheet.Columns [K + 2] .NumberFormat:= AnsiChar('@'); 
sheet.Columns [K + 2] .NumberFormat:= AnsiString('m / d / yyyy');


I'm exporting data from a CxDBGrid to an Excel file. I'm able to create the file and copy data in it, but I'm having real trouble with the column formatting. Since I'm pulling the data from a DB I'd like the spreadsheet to reflect the type: NUMBER, VARCHAR2,DATE and so on. I visually created a macro, went to look for the VBA code, and replicated it in the Delphi project:

sheet.Columns[K+2].NumberFormat := '0,000'; //Number
sheet.Columns[K+2].NumberFormat := '@'; //Text
sheet.Columns[K+2].NumberFormat := 'm/d/yyyy'; //Date

Number formatting works ok most of the times, but the other two don't. When I open the generated file, the text columns show up as type "Custom" and every cell displays "-64". If I go to edit a cell, the correct value is actually there. Date is another issue: the DB's format is dd/mm/yyyy and if I feed it to Excel as-is, it gets all messed up. I tried setting the correct format, but then Excel doesn't recognize it.

Any clues?

I'm also setting column width. That works flawlessly.

解决方案

The problem is that the assigned values are Unicode strings. Try this:

sheet.Columns[K+2].NumberFormat := AnsiChar('@');
sheet.Columns[K+2].NumberFormat := AnsiString('m/d/yyyy');

这篇关于如何设置Excel列类型和格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆