我找到了一个打开的 source project使用基本的 excel 功能,写入单元格,写入单元格,更改颜色,字体和内容。缺少一件事,它添加了公式,我无法实现它,所以如果有人知道如何去做那就太好了。
BIFF 格式:
internal sealed class BIFF
{
public const ushort DefaultColor = 0x7fff;
public const ushort BOFRecord = 0x0209;
public const ushort EOFRecord = 0x0A;
public const ushort FontRecord = 0x0231;
public const ushort FormatRecord = 0x001E;
public const ushort LabelRecord = 0x0204;
public const ushort WindowProtectRecord = 0x0019;
public const ushort XFRecord = 0x0243;
public const ushort HeaderRecord = 0x0014;
public const ushort FooterRecord = 0x0015;
public const ushort ExtendedRecord = 0x0243;
public const ushort StyleRecord = 0x0293;
public const ushort CodepageRecord = 0x0042;
public const ushort NumberRecord = 0x0203;
public const ushort ColumnInfoRecord = 0x007D;
}
int和string的写法示例
private void WriteStringCell(BinaryWriter writer, CellInfo cell)
{
string value;
if (cell.Value is string)
value = (string)cell.Value;
else
value = cell.Value.ToString();
if (value.Length > 255)
value = value.Substring(0, 255);
ushort[] clData = { BIFF.LabelRecord, 0, 0, 0, 0, 0 };
byte[] plainText = Encoding.GetEncoding(CodePage).GetBytes(value);
int iLen = plainText.Length;
clData[1] = (ushort)(8 + iLen);
clData[2] = (ushort)cell.Row;
clData[3] = (ushort)cell.Column;
clData[4] = (ushort)cell.FXIndex;
clData[5] = (ushort)iLen;
WriteUshortArray(writer, clData);
writer.Write(plainText);
}
private void WriteNumberCell(BinaryWriter writer, CellInfo cell)
{
double dValue = Convert.ToDouble(cell.Value);
ushort[] clData = { BIFF.NumberRecord, 14, (ushort)cell.Row, (ushort)cell.Column, (ushort)cell.FXIndex };
WriteUshortArray(writer, clData);
writer.Write(dValue);
}
您可以从提供的链接下载源代码。所以我想要的是有一个方法 WriteFromulaCell 可以将公式写入 excel。完全没有成功。
提前致谢。
最佳答案
BIFF 中的公式表示为 token 的二进制流。如果你想做的是创建一个 WriteFormulaCell() ,它可以接受像“=SUM(A3:Q47)”这样的字符串并将其转换为有效的 FORMULA 记录,那需要几个月或几年的工作工作,取决于。此外,他们用于 token 的字节码也发生了几次变化——BIFF 的每个版本都对其编码方式进行了一些更改。
如果您要做的是在特定位置插入特定的简单公式,请启动 Excel,将公式键入空电子表格的正确位置,另存为 Excel 97,然后查看BIFF 文件。您会找到一个包含正确解析的 token 流的 FORMULA 记录,您可以将其复制并插入到您自己的文件中。我假设您了解整个相对引用/绝对引用。对其他工作表的引用将按索引,而不是按名称。定义的名称根本无法使用此技巧。其他限制可能适用,您的里程可能会有所不同,没有暗示保证等。
关于c# - 如何将公式写入excel二进制文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8759479/