winform中 如何读取Excel文件,之后再把它写入一个新的Excel文件
如题,请问各位高手,winform中 如何读取Excel文件,之后再把它写入一个新的Excel文件。
最好可以给我一个简单的例子看一下。
谢谢。
------解决方案--------------------把数据读出Excle:
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
for (int i = 1; i <= ds.Tables[0].Columns.Count; i++)
{
excel.Cells[1, i] = ds.Tables[0].Columns[i - 1].ColumnName.ToString();
}
for (int i = 2; i <= ds.Tables[0].Rows.Count + 1; i++)
{
for (int j = 1; j <= ds.Tables[0].Columns.Count; j++)
{
excel.Cells[i, j] = ds.Tables[0].Rows[i - 2][j - 1].ToString();
}
}
excel.Visible = true;
把数据导入Excle:
public void DBWriteToExcel(DataSet myds)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Application.ExecutablePath;
saveFileDialog1.Filter = "Microsoft Office Excel 工作薄(*.xls)|*.xls ";
saveFileDialog1.OverwritePrompt = true;
saveFileDialog1.FileName = "客服日报查询结果 ";//dtpBegin.Text + "至 " + dtpEnd.Text + "客服日报查询结果 ";
if ((saveFileDialog1.ShowDialog()) == DialogResult.OK)
{
FileStream fs = new FileStream(saveFileDialog1.FileName, FileMode.Create);
StreamWriter writer = new StreamWriter(fs, Encoding.Unicode);
try
{
//取得数据表各列标题,各标题之间以\t分割,最后一个列标题后加回车符
StringBuilder colHeaders = new StringBuilder();
for (int i = 0; i < myds.Tables[0].Columns.Count; i++)
{
colHeaders.Append(myds.Tables[0].Columns[i].Caption.ToString() + "\t ");
//colHeaders += myds.Tables[0].Columns[i].Caption.ToString() + "\t ";
}
colHeaders.Append( "\n ");
//输出流中写入取得的数据信息
writer.Write(colHeaders.ToString());
//逐行处理数据
StringBuilder ls_item = new StringBuilder();
for (int i = 0; i < myds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < myds.Tables[0].Columns.Count; j++)
{
ls_item.Append(myds.Tables[0].Rows[i][j].ToString().Replace( "\n ", " ").Replace( "\t ", " ") + "\t "); ;
}
ls_item.Append( "\n ");
}
//当前行数据写入HTTP输出流,并且置空ls_item以便下行数据
writer.Write(ls_item.ToString());
}
catch (Exception excep)
{
MessageBox.Show(excep.Message);
}
finally
{
writer.Flush();
writer.Close();
fs.Close();
}
}
}