如果您想要持久的单元格格式,则以下类型的对象序列化将适合您。
创建一个类来序列化您所需的属性:
public class SavedSettings
{
[XmlIgnore]
public Color ForeColor { get; set; }
[XmlElement("ForeColor")]
public int ForeColorARGB
{
get { return this.ForeColor.ToArgb(); }
set { this.ForeColor = Color.FromArgb(value); }
}
[XmlIgnore]
public Color BackColor { get; set; }
[XmlElement("BackColor")]
public int BackColorARGB
{
get { return this.BackColor.ToArgb(); }
set { this.BackColor = Color.FromArgb(value); }
}
public object Value { get; set; }
}
在您的主类中,从 xml 加载所有已保存的设置:
public List<SavedSettings> Settings { get; set; }
private void ReadXML()
{
System.Xml.Serialization.XmlSerializer reader =
new System.Xml.Serialization.XmlSerializer(typeof(List<SavedSettings>));
if (File.Exists(@"SavedSettings.xml"))
{
System.IO.StreamReader file = new System.IO.StreamReader(
@"SavedSettings.xml");
this.Settings = (List<SavedSettings>)reader.Deserialize(file);
file.Close();
}
}
private void LoadDGV()
{
this.ReadXML();
if (this.Settings != null)
{
// This assumes your dgv has added columns already.
int rows = this.Settings.Count / this.dataGridView1.Columns.Count;
int cols = this.dataGridView1.Columns.Count;
this.dataGridView1.Rows.AddCopies(0, rows);
for (int i = 0; i < this.Settings.Count; i++)
{
int row = i / cols;
int col = i % cols;
this.dataGridView1[col, row].Style.BackColor = this.Settings[i].BackColor;
this.dataGridView1[col, row].Style.ForeColor = this.Settings[i].ForeColor;
this.dataGridView1[col, row].Value = this.Settings[i].Value;
}
}
}
然后,当您准备好保存时,将单元格设置重新加载到对象数组中并将其序列化:
private void SaveSettings()
{
this.Settings = new List<SavedSettings>();
foreach (DataGridViewRow row in this.dataGridView1.Rows)
{
if (!row.IsNewRow)
{
foreach (DataGridViewCell cell in row.Cells)
{
SavedSettings setting = new SavedSettings();
setting.BackColor = cell.Style.BackColor.ToArgb() == 0 ? Color.White : cell.Style.BackColor;
setting.ForeColor = cell.Style.ForeColor.ToArgb() == 0 ? Color.Black : cell.Style.ForeColor; ;
setting.Value = cell.Value;
this.Settings.Add(setting);
}
}
}
this.WriteXML();
}
private void WriteXML()
{
System.Xml.Serialization.XmlSerializer writer =
new System.Xml.Serialization.XmlSerializer(typeof(List<SavedSettings>));
System.IO.StreamWriter file = new System.IO.StreamWriter(@"SavedSettings.xml");
writer.Serialize(file, this.Settings);
file.Close();
}
Note这将允许某些属性持续存在。当然有更好的方法,我很想在时间允许的情况下学习它们,但是这个例子can做这份工作。至于额外的 Excel 要求,我到目前为止还没有尝试过。我将补充您的问题以反映吸引面向 Excel 的答案的要求。