1.需要添加的引用
2.新建Xml转换为DataTable类
class XmlToDataTableHepler
{
/// <summary>
/// 存储到指定位置下
/// </summary>
/// <param name="filename">指定位置下文件名</param>
/// <param name="dt">dataTable转换成Xml</param>
public static void SaveXml(string filename,DataTable dt)
{
string strXml = ConvertDataTableToXml(dt);
#region 写入数据
using (FileStream fsWrite = new FileStream(filename, FileMode.OpenOrCreate, FileAccess.Write))
{
byte[] buffer = Encoding.Default.GetBytes(strXml);
fsWrite.Write(buffer, 0, buffer.Length);
}
#endregion
}
/// <summary>
/// dataTable转换成Xml
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
private static string ConvertDataTableToXml(DataTable dt)
{
StringBuilder strXml = new StringBuilder();
strXml.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
strXml.AppendLine("<ArrayOfHAHAData>");
for (int i = 0; i < dt.Rows.Count; i++)
{
strXml.AppendLine("<HAHAData>");
for (int j = 0; j < dt.Columns.Count; j++)
{
strXml.AppendLine("<" + dt.Columns[j].ColumnName + ">" + dt.Rows[i][j] + "</" + dt.Columns[j].ColumnName + ">");
}
strXml.AppendLine("</HAHAData>");
}
strXml.AppendLine("</ArrayOfHAHAData>");
return strXml.ToString();
}
/// <summary>
/// 读取xml文件转换成DataTable
/// </summary>
/// <param name="fileName">指定位置下文件名</param>
/// <returns></returns>
public static DataTable ConvertXmlToDataTable(string fileName)
{
DataTable dt = null;
DataSet DS = new DataSet();
DS.ReadXml(fileName);
dt = DS.Tables[0];
return dt;
}
}
3.新建一个DataTable转换Excel类
此类参考博客 C#导入导出EXCEL实例包括2003和2007以上版本-罗分明网络博客
class ExcelHepler
{
/// <summary>
/// 从Excel读取数据
/// 只支持单表
/// </summary>
/// <param name="FilePath">文件路径</param>
public static DataTable ReadFromExcel(string FilePath)
{
DataTable result = null;
IWorkbook wk = null;
string extension = System.IO.Path.GetExtension(FilePath); //获取扩展名
try
{
using (FileStream fs = File.OpenRead(FilePath))
{
if (extension.Equals(".xls")) //2003
{
wk = new HSSFWorkbook(fs);
}
else //2007以上
{
wk = new XSSFWorkbook(fs);
}
}
//读取当前表数据
ISheet sheet = wk.GetSheetAt(0);
//构建DataTable
IRow row = sheet.GetRow(0);
result = BuildDataTable(row);
if (result != null)
{
if (sheet.LastRowNum >= 1)
{
for (int i = 1; i < sheet.LastRowNum + 1; i++)
{
IRow temp_row = sheet.GetRow(i);
if (temp_row == null) { continue; }//2019-01-14 修复 行为空时会出错
List<object> itemArray = new List<object>();
for (int j = 0; j < result.Columns.Count; j++)//解决Excel超出DataTable列问题 lqwvje20181027
{
//itemArray.Add(temp_row.GetCell(j) == null ? string.Empty : temp_row.GetCell(j).ToString());
itemArray.Add(GetValueType(temp_row.GetCell(j)));//解决 导入Excel 时间格式问题 lqwvje 20180904
}
result.Rows.Add(itemArray.ToArray());
}
}
}
return result;
}
catch (Exception ex)
{
return null;
}
}
/// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public static int DataTableToExcel(DataTable data, string sheetName, string fileName, bool isColumnWritten)
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null;
IWorkbook workbook = null;
using (FileStream fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook();
try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
}
if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
}
for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -1;
}
}
}
private static DataTable BuildDataTable(IRow Row)
{
DataTable result = null;
if (Row.Cells.Count > 0)
{
result = new DataTable();
for (int i = 0; i < Row.LastCellNum; i++)
{
if (Row.GetCell(i) != null)
{
result.Columns.Add(Row.GetCell(i).ToString());
}
}
}
return result;
}
/// <summary>
/// 获取单元格类型
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueType(ICell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
short format = cell.CellStyle.DataFormat;
if (format != 0) { return Convert.ToDateTime(cell.DateCellValue).ToString("yyyy-MM-dd HH:mm:ss"); } else { return cell.NumericCellValue; }
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
}
4.应用
private void button4_Click(object sender, EventArgs e)
{
DataTable dataTabale = null;
string path = AppDomain.CurrentDomain.BaseDirectory + "Al.xlsx";
dataTabale = ExcelHepler.ReadFromExcel(path);
dataGridView1.DataSource = dataTabale;
string path2 = AppDomain.CurrentDomain.BaseDirectory + "A25.xml";
XmlToDataTableHepler.SaveXml(path2, dataTabale);
MessageBox.Show("success");
}
private void btnReadXml_Click(object sender, EventArgs e)
{
string path2 = AppDomain.CurrentDomain.BaseDirectory + "Al.xml";
string fileName = AppDomain.CurrentDomain.BaseDirectory + "HeyHi.xlsx";
DataTable dt = XmlToDataTableHepler.ConvertXmlToDataTable(path2);
dataGridView1.DataSource = dt;
ExcelHepler.DataTableToExcel(dt,"hello",fileName,true);
MessageBox.Show("success");
}