[英]C# SpreadsheetLight corrupts excel file after save
由于在 .network 上运行 .xlsm 文件的一些问题,决定不再使用 VBA 并开发将编辑常规 excel 文件的独立应用程序。 由于我有一些 C# 和 Visual Studio 知识,所以我决定使用这些工具。 由于 Iterop.Excel 真的很慢,我决定使用 SpreadsheetLight。
在读取和分析数据期间一切顺利,但在我添加了一些记录并保存文件后,文件损坏了:当尝试使用 excel 打开时,我收到以下消息:
“我们发现某些内容存在问题。您希望我们尽可能多地恢复吗?如果您信任此工作簿的来源,请单击是”。 单击“是”后,收到消息称它已损坏,无法恢复。
即使我不添加任何记录而只是保存文件也已损坏。
问题是文件在 OpenOffice 中打开时没有任何问题,所有记录都在那里。
任何帮助将不胜感激!
下面的class实现了excel文件的r/w:
class SPREADSHEET_TOOLS
{
public string file_name;
public SLDocument doc;
public List<string> sheets;
MemoryStream ms;
public SPREADSHEET_TOOLS()
{
}
public bool init(string _file_name)
{
this.file_name = _file_name;
ms = new MemoryStream();
try
{
FileStream stream = File.Open(this.file_name, FileMode.Open);
this.doc = new SLDocument(stream);
this.sheets = doc.GetSheetNames();
stream.Close();
}
catch (IOException)
{
MessageBox.Show("Fisierul este deschis de un alt utilizator. Nu poate fi accesat!!!!");
return false;
}
return true;
}
public List<string>getUniqeRowValues(string sheet,int row)
{
List<string> values = new List<string>();
if (this.sheets.Contains(sheet))
{
this.doc.SelectWorksheet(sheet);
while (this.doc.GetCellValueAsString(row, 1) != "")
{
if (values.Count == 0)
{
values.Add(this.doc.GetCellValueAsString(row, 1));
}
else
{
if (!values.Contains(this.doc.GetCellValueAsString(row, 1)))
{
values.Add(this.doc.GetCellValueAsString(row, 1));
}
}
row++;
}
}
return values;
}
public List<string>getChildValues(string sheet, string parent, int row, int column_parent, int column_child)
{
List<string> values = new List<string>();
if (this.sheets.Contains(sheet))
{
this.doc.SelectWorksheet(sheet);
while (this.doc.GetCellValueAsString(row, column_parent) != "")
{
if (this.doc.GetCellValueAsString(row, column_parent) == parent)
{
values.Add(this.doc.GetCellValueAsString(row, column_child));
}
row++;
}
}
return values;
}
public int getLastRow(string sheet)
{
int row=0;
if (this.sheets.Contains(sheet))
{
this.doc.SelectWorksheet(sheet);
row = 1;
while (this.doc.GetCellValueAsString(row, 1) != "")
{
row++;
}
}
return row;
}
public bool writeRow(string[] data, string sheet,int row)
{
if (this.sheets.Contains(sheet))
{
this.doc.SelectWorksheet(sheet);
for (int i=0; i < data.Length; i++)
{
InlineString str = new InlineString();
//bool a = this.doc.SetCellValue(row,i+1,data[i]);
}
//this.doc.SaveAs(this.ms);
foreach (string s in this.sheets)
{
this.doc.SelectWorksheet(s);
}
this.doc.DocumentProperties.Creator = "CP";
this.doc.SaveAs("E:\\C-SHARP\\PONTAJ\\PONTAJ\\BUBU.XLSX");
MessageBox.Show("Saved!");
return true;
}
return false;
}
}
我也遇到了同样的问题,Excel 文件在下载后损坏。 所以我做了一些修复并将 SpreadSheetLight 代码更新为 .NET 6。
您可以从这里下载源代码: https://github.com/bhavinvachhani403/SpreadSheetLight_Net6.0
我希望这会帮助你解决你的问题。
我有同样的错误,我通过将 DocumentFormat.OpenXml 的版本更改为 2.5 版来解决它
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.