最近工作需要写一个小工具,对会员卡卡号进行修改,需要修改的会员卡号存放在excel中,其中有id,正确卡号,当前错误卡号,状态 4列,为了不让用户随意修改excel内容,需要将excel转化为xml,然后对xml进行加密,在程序中读取xml内容,放到字符串中,进行解密,然后在读卡后,查找xml是否有对应的错误卡号,如果有将卡号修改为正确卡号,然后修改成功后需要将这张卡的状态置为已修改。
/// <summary>
/// 使用NPOI读取excel,将数据放到新创建的xml中
/// </summary>
/// <param name="filePath">excel路径</param>
private void ExportExcel(string filePath)
{
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(dec);
//创建一个根节点
XmlElement root = doc.CreateElement("CardsInfo");
doc.AppendChild(root);
IWorkbook wk = null;
string extension = System.IO.Path.GetExtension(filePath);//获取扩展名
try
{
FileStream fs = File.OpenRead(filePath);
//if(extension.Equals)
if (extension.Equals(".xls"))
{
//把xls文件中的数据写入wk中
wk = new HSSFWorkbook(fs);
}
fs.Close();
ISheet sheet = wk.GetSheetAt(0);
IRow row = sheet.GetRow(1);//获取当前行数据
for (int i = 2; i <= sheet.LastRowNum; i++)
{
row = sheet.GetRow(i); //读取当前行数据
if (row != null)
{
//LastCellNum 是当前行的总列数
XmlElement node = doc.CreateElement("Card");
node.SetAttribute("ID", row.GetCell(0).ToString());
node.SetAttribute("CorrectCardNum", row.GetCell(1).ToString());
node.SetAttribute("ErrorCardNum", row.GetCell(2).ToString());
node.SetAttribute("Satus", "");
root.AppendChild(node);
}
}
doc.Save("bb.xml");
Console.Write(doc.OuterXml);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
//现在的bb.xml是明文的,为了安全,需要对其加密,使用AES加密
/// <summary>
/// 将xml转化为字符串,然后进行AES加密,存到aes.xml中
/// </summary>
private void xmlToString()
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load("bb.xml");//加载xml文件
string aesCardInfo=AES.Encrypt(xdoc.InnerXml);将内容进行加密
FileStream fs = new FileStream("aes.xml", FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
sw.Write(aesCardInfo);
sw.Flush();
sw.Close();
}
到目前为止,我们用的aes.xml是乱码的,用户不知道这个文件xml存了什么,相对安全
//下面是读取aes.xml,解密,并进行一些操作