? ? ? ?首先說一下需求,用戶需要將一個(gè)報(bào)表的數(shù)據(jù)導(dǎo)出到指定的excel模板,再將這個(gè)excel模板發(fā)給客戶,客戶填寫信息后,用戶再使用該界面進(jìn)行導(dǎo)入反寫。主要功能為查詢、導(dǎo)出、導(dǎo)入與保存。
? ? ? (1)查詢功能,這個(gè)就是從數(shù)據(jù)庫中查詢數(shù)據(jù)再顯示到gridControl1上,就不貼代碼了。
? ? ? (2)導(dǎo)出功能,C#操作excel有很多方法,例如?Microsoft.Office.Interop.Excel? 、Aspose.cells、NPOI等,我選的是引用?Microsoft.Office.Interop.Excel。注意:這個(gè)組件的索引是從1開始的!
? ? ? ??
/// <summary>
/// 導(dǎo)出數(shù)據(jù)至excel模板(使用Microsoft.Office.Interop.Excel組件的方式)
/// </summary>
public void ExportExcel(DataTable DT)
{
try
{
//需要添加 Microsoft.Office.Interop.Excel引用
Microsoft.Office.Interop.Excel.Application app = new
Microsoft.Office.Interop.Excel.Application();
if (app == null)//服務(wù)器上缺少Excel組件,需要安裝Office軟件
{
return;
}
app.Visible = false;
app.UserControl = true;
//添加模板至項(xiàng)目啟動(dòng)的debug文件夾中
string strTempPath = Application.StartupPath + @"\OfficeTemplate\模版.xls";
Microsoft.Office.Interop.Excel.Workbooks workbooks = app.Workbooks;
Microsoft.Office.Interop.Excel._Workbook workbook = workbooks.Add(strTempPath); //加載模板
Microsoft.Office.Interop.Excel.Sheets sheets = workbook.Sheets;
Microsoft.Office.Interop.Excel._Worksheet worksheet =
(Microsoft.Office.Interop.Excel._Worksheet)sheets.get_Item(1); //第一個(gè)工作薄。
if (worksheet == null)//工作薄中沒有工作表
{
return;
}
//1、獲取數(shù)據(jù)
int rowCount = DT.Rows.Count;
if (rowCount < 1)//沒有取到數(shù)據(jù)
{
return;
}
//表頭信息
worksheet.Cells[5, 3] = DT.Rows[0]["日期"].ToString();
worksheet.Cells[5, 10] = DT.Rows[0]["名稱"].ToString();
//此項(xiàng)目需要先插入需要的行 再進(jìn)行賦值
object MisValue = Type.Missing;
for (int i = 1; i <= rowCount; i++)
{
//從第八行開始新增 插入一行
Microsoft.Office.Interop.Excel.Range xlsRows =
(Microsoft.Office.Interop.Excel.Range)worksheet.Rows[9, MisValue];
xlsRows.Insert(Microsoft.Office.Interop.Excel.XlInsertShiftDirection.xlShiftDown, MisValue);
}
//2、寫入數(shù)據(jù),Excel索引從1開始
for (int i = 1; i <= rowCount; i++)
{
int row_ = 7 + i; //Excel模板上表頭占了1行
int dt_row = i - 1; //dataTable的行是從0開始的
worksheet.Cells[row_, 1] = DT.Rows[dt_row]["列名1"].ToString();
worksheet.Cells[row_, 2] = DT.Rows[dt_row]["列名2"].ToString();
worksheet.Cells[row_, 3] = DT.Rows[dt_row]["列名3"].ToString();
worksheet.Cells[row_, 4] = DT.Rows[dt_row]["列名4"].ToString();
/* 此為注釋內(nèi)容無需注意
string strNum = DT.Rows[dt_row]["數(shù)量"].ToString() == "" ? "0" :
DT.Rows[dt_row]["數(shù)量"].ToString();
if (strNum.Contains("."))
{//字符串為浮點(diǎn)數(shù)
strNum = strNum.TrimEnd('0').TrimEnd('.');//1.00000
}
amount = amount + Convert.ToInt32(strNum);*/
}
//設(shè)置導(dǎo)出文件路徑
//string dir = System.Environment.CurrentDirectory;//當(dāng)前工作目錄完全限定
string dir = System.Environment.SystemDirectory;//系統(tǒng)目錄的
string filePath = FileDialogHelper.SaveExcel("需要填寫的文件名", dir);
if (!string.IsNullOrEmpty(filePath))
{
try
{
//保存生成的Excel文件
workbook.SaveAs(filePath, Missing.Value, Missing.Value,
Missing.Value, Missing.Value, Missing.Value,
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange,
Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
Msg.ShowInformation("保存成功");
workbook.Close();
}
catch (Exception ex)
{
Msg.ShowException(ex);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
?
//保存excel的類
public class FileDialogHelper
{
public static string SaveExcel(string file, string path)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = path;
// saveFileDialog.Filter = "excel2003|*.xls|excel2007|*.xlsx";
saveFileDialog.Filter = "excel2007|*.xls|excel2003|*.xlsx";
saveFileDialog.RestoreDirectory = true;
saveFileDialog.FileName = file;//文件名賦值
saveFileDialog.FilterIndex = 1;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
return saveFileDialog.FileName;
}
return "";
}
}
(3)導(dǎo)入功能,我選擇引用Aspose.cells來導(dǎo)入數(shù)據(jù)。注意:這個(gè)組件的索引是從0開始的!文章來源:http://www.zghlxwxcb.cn/news/detail-619436.html
private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
try
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string _filePath = openFileDialog1.FileName;
if (_filePath != "")
{
using (FileStream fs = new FileStream(_filePath, FileMode.Open, FileAccess.Read))
{
DataTable dt = Table();
Workbook wk = new Workbook();//工作簿
wk.Open(fs); //打開excel文檔
Worksheet worksheet = wk.Worksheets[0];//工作表
Cells cells = worksheet.Cells;//獲取worksheet所有單元格
//判斷excel導(dǎo)入格式
if (!cells[4, 1].StringValue.Contains("日期"))
{
MessageBox.Show("導(dǎo)入的文檔格式不對,請選擇正確格式的文檔導(dǎo)入!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
return;
}
//循環(huán)遍歷所有單元格信息
for (int i = 7; i <= cells.Rows.Count; i++)
{
if (string.IsNullOrEmpty(cells[i, 0].StringValue.Trim()))
{
break;
}
DataRow dr = dt.NewRow();
dr["表頭1"] = cells[4, 2].StringValue.Trim();
dr["表頭2"] = cells[4, 5].StringValue.Trim();
dr["表頭3"] = cells[4, 7].StringValue.Trim();
dr["表頭4"] = cells[4, 9].StringValue.Trim();
dr["列名1"] = cells[i, 0].StringValue.Trim();
dr["列名2"] = cells[i, 1].StringValue.Trim();
dr["列名3"] = cells[i, 2].StringValue.Trim();
dr["列名4"] = cells[i, 3].StringValue.Trim();
dt.Rows.Add(dr);
}
gridControl1.DataSource = dt;
gridView1.BestFitColumns();
}
}
}
}
catch (Exception es)
{
MessageBox.Show(es.ToString());
}
}
?文章來源地址http://www.zghlxwxcb.cn/news/detail-619436.html
到了這里,關(guān)于C# 將Datatable的數(shù)據(jù)導(dǎo)出至指定的excel模板案例的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!