Excel格式问题的处理

问题

  1. Excel中的日期自动变成整数
  2. 设置的边框等格式在重新打开后消失
  3. 操作反应变慢

原因分析

在Excel中多次的复制粘贴、修改样式会不断积累许多单元格的样式设置,当样式过多时就可能出现混乱的情况。

解决办法

经过实践,可以将样式删除后重新设置格式即可恢复正常。但普通的删除方法通过遍历处理可能会非常的慢,比如以下的代码,通过VBA来处理,有些文档样式几百上千个的时候慢得很:

Application.ScreenUpdating=False
Dim mystyle As Style
On Error Resume Next
For Each mystyle In ActiveWorkbook.Styles
    If mystyle.BuiltIn = False Then mystyle.Delete
Next
Application.ScreenUpdating=True

2007及以后的版本文件都是一个压缩包,里面包含了各种文件,其中就有一个styles.xml文件,里面保存了工作表的各种样式,只要将其删除掉就可以了。思路就是将文件保存为xlsx格式,然后解压,再找到styles.xml,删除样式。

C#处理的代码:

            string excelpath = txtInputFile.Text;//这里用文件选择框选择赋值
            if (File.Exists(excelpath))
            {
                txtOutFilePath.Text = "";
                btnOpenFile.Enabled = false;
                try
                {
                    FileInfo fileinfo = new FileInfo(excelpath);

                    string newFileName = fileinfo.FullName.Substring(0, fileinfo.FullName.Length - fileinfo.Extension.Length) + "_noStyle" + fileinfo.Extension;
                    //newFileName是另存的文件名
                    string bakPath = fileinfo.Directory.ToString() + @"\Tmp";
                    //备份
                    File.Copy(excelpath, newFileName);
                    //解压
                    (new FastZip()).ExtractZip(newFileName, bakPath, "");
                    //替换Styles
                    string xmlPath = bakPath + @"\xl\styles.xml";
                    string style = File.ReadAllText(xmlPath, Encoding.UTF8);
                    Regex regex = new Regex(@"<cellStyles.*</cellStyles>", RegexOptions.IgnoreCase);
                    string result = regex.Replace(style, "");
                    File.WriteAllText(xmlPath, result, Encoding.UTF8);
                    //压缩
                    (new FastZip()).CreateZip(newFileName, bakPath, true, "");

                    //删除文件夹
                    DirectoryInfo di = new DirectoryInfo(bakPath);
                    di.Delete(true);
                    txtOutFilePath.Text = newFileName;
                    btnOpenFile.Enabled = true;
                    MessageBox.Show("删除成功!\n\n删除样式后的文件:" + newFileName, "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message, "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("文件不存在!", "温馨提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

这样处理的话速度快很多。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Hello World,

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值