问题
- Excel中的日期自动变成整数
- 设置的边框等格式在重新打开后消失
- 操作反应变慢
原因分析
在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);
}
这样处理的话速度快很多。